diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index 2672a1709a3..c46875f9fb4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -48,6 +48,7 @@ public class CodegenOperation { public List cookieParams = new ArrayList(); public List requiredParams = new ArrayList(); public List optionalParams = new ArrayList(); + public List requiredAndNotNullableParams = new ArrayList(); public List authMethods; public List tags; public List responses = new ArrayList(); @@ -157,6 +158,10 @@ public class CodegenOperation { return nonEmpty(optionalParams); } + public boolean getHasRequiredAndNotNullableParams() { + return nonEmpty(requiredAndNotNullableParams); + } + /** * Check if there's at least one required parameter * @@ -364,6 +369,7 @@ public class CodegenOperation { sb.append(", cookieParams=").append(cookieParams); sb.append(", requiredParams=").append(requiredParams); sb.append(", optionalParams=").append(optionalParams); + sb.append(", requiredAndNotNullableParams=").append(requiredAndNotNullableParams); sb.append(", authMethods=").append(authMethods); sb.append(", tags=").append(tags); sb.append(", responses=").append(responses); @@ -442,6 +448,7 @@ public class CodegenOperation { Objects.equals(cookieParams, that.cookieParams) && Objects.equals(requiredParams, that.requiredParams) && Objects.equals(optionalParams, that.optionalParams) && + Objects.equals(requiredAndNotNullableParams, that.requiredAndNotNullableParams) && Objects.equals(authMethods, that.authMethods) && Objects.equals(tags, that.tags) && Objects.equals(responses, that.responses) && @@ -471,6 +478,6 @@ public class CodegenOperation { pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, returnProperty, optionalParams, authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs, vendorExtensions, nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, - operationIdSnakeCase, hasErrorResponseObject); + operationIdSnakeCase, hasErrorResponseObject, requiredAndNotNullableParams); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index ca8ac29eb31..ae723856989 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -763,10 +763,14 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { this.requiredVars = requiredVars; } - public boolean compulsory(){ + public boolean requiredAndNotNullable(){ return required && !isNullable; } + public boolean notRequiredOrIsNullable() { + return !required || isNullable; + } + @Override public boolean getIsNull() { return isNull; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index c3cf38349bb..d3de34a29ba 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -505,7 +505,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti return required; } - public boolean compulsory() { + public boolean requiredAndNotNullable() { return getRequired() && !isNullable; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 0e580ae31d4..30e1c099c5e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -4332,6 +4332,7 @@ public class DefaultCodegen implements CodegenConfig { List formParams = new ArrayList<>(); List requiredParams = new ArrayList<>(); List optionalParams = new ArrayList<>(); + List requiredAndNotNullableParams = new ArrayList<>(); CodegenParameter bodyParam = null; RequestBody requestBody = operation.getRequestBody(); @@ -4441,6 +4442,10 @@ public class DefaultCodegen implements CodegenConfig { optionalParams.add(cp.copy()); op.hasOptionalParams = true; } + + if (cp.requiredAndNotNullable()) { + requiredAndNotNullableParams.add(cp.copy()); + } } // add imports to operation import tag @@ -4477,6 +4482,7 @@ public class DefaultCodegen implements CodegenConfig { op.formParams = formParams; op.requiredParams = requiredParams; op.optionalParams = optionalParams; + op.requiredAndNotNullableParams = requiredAndNotNullableParams; op.externalDocs = operation.getExternalDocs(); // legacy support op.nickname = op.operationId; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index 76075c09862..184df911737 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -400,19 +400,35 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { // avoid breaking changes if (GENERICHOST.equals(getLibrary())) { - Comparator comparatorByRequiredAndDefault = propertyComparatorByRequired.thenComparing(propertyComparatorByDefaultValue); - Collections.sort(codegenModel.vars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.allVars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.requiredVars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.optionalVars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.readOnlyVars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.readWriteVars, comparatorByRequiredAndDefault); - Collections.sort(codegenModel.parentVars, comparatorByRequiredAndDefault); + + Collections.sort(codegenModel.vars, propertyComparatorByName); + Collections.sort(codegenModel.allVars, propertyComparatorByName); + Collections.sort(codegenModel.requiredVars, propertyComparatorByName); + Collections.sort(codegenModel.optionalVars, propertyComparatorByName); + Collections.sort(codegenModel.readOnlyVars, propertyComparatorByName); + Collections.sort(codegenModel.readWriteVars, propertyComparatorByName); + Collections.sort(codegenModel.parentVars, propertyComparatorByName); + + Comparator comparator = propertyComparatorByNullable.thenComparing(propertyComparatorByDefaultValue); + Collections.sort(codegenModel.vars, comparator); + Collections.sort(codegenModel.allVars, comparator); + Collections.sort(codegenModel.requiredVars, comparator); + Collections.sort(codegenModel.optionalVars, comparator); + Collections.sort(codegenModel.readOnlyVars, comparator); + Collections.sort(codegenModel.readWriteVars, comparator); + Collections.sort(codegenModel.parentVars, comparator); } return codegenModel; } + public static Comparator propertyComparatorByName = new Comparator() { + @Override + public int compare(CodegenProperty one, CodegenProperty another) { + return one.name.compareTo(another.name); + } + }; + public static Comparator propertyComparatorByDefaultValue = new Comparator() { @Override public int compare(CodegenProperty one, CodegenProperty another) { @@ -425,18 +441,25 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } }; - public static Comparator propertyComparatorByRequired = new Comparator() { + public static Comparator propertyComparatorByNullable = new Comparator() { @Override public int compare(CodegenProperty one, CodegenProperty another) { - if (one.required == another.required) + if (one.isNullable == another.isNullable) return 0; - else if (Boolean.TRUE.equals(one.required)) + else if (Boolean.FALSE.equals(one.isNullable)) return -1; else return 1; } }; + public static Comparator parameterComparatorByDataType = new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + return one.dataType.compareTo(another.dataType); + } + }; + public static Comparator parameterComparatorByDefaultValue = new Comparator() { @Override public int compare(CodegenParameter one, CodegenParameter another) { @@ -804,8 +827,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authPackageDir, "OAuthFlow.cs")); } } - - addTestInstructions(); } public void setClientPackage(String clientPackage) { @@ -823,45 +844,34 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { return op; } - Comparator comparatorByRequiredAndDefault = parameterComparatorByRequired.thenComparing(parameterComparatorByDefaultValue); - Collections.sort(op.allParams, comparatorByRequiredAndDefault); - Collections.sort(op.bodyParams, comparatorByRequiredAndDefault); - Collections.sort(op.pathParams, comparatorByRequiredAndDefault); - Collections.sort(op.queryParams, comparatorByRequiredAndDefault); - Collections.sort(op.headerParams, comparatorByRequiredAndDefault); - Collections.sort(op.implicitHeadersParams, comparatorByRequiredAndDefault); - Collections.sort(op.formParams, comparatorByRequiredAndDefault); - Collections.sort(op.cookieParams, comparatorByRequiredAndDefault); - Collections.sort(op.requiredParams, comparatorByRequiredAndDefault); - Collections.sort(op.optionalParams, comparatorByRequiredAndDefault); + Collections.sort(op.allParams, parameterComparatorByDataType); + Collections.sort(op.bodyParams, parameterComparatorByDataType); + Collections.sort(op.pathParams, parameterComparatorByDataType); + Collections.sort(op.queryParams, parameterComparatorByDataType); + Collections.sort(op.headerParams, parameterComparatorByDataType); + Collections.sort(op.implicitHeadersParams, parameterComparatorByDataType); + Collections.sort(op.formParams, parameterComparatorByDataType); + Collections.sort(op.cookieParams, parameterComparatorByDataType); + Collections.sort(op.requiredParams, parameterComparatorByDataType); + Collections.sort(op.optionalParams, parameterComparatorByDataType); + Collections.sort(op.requiredAndNotNullableParams, parameterComparatorByDataType); + + Comparator comparator = parameterComparatorByRequired.thenComparing(parameterComparatorByDefaultValue); + Collections.sort(op.allParams, comparator); + Collections.sort(op.bodyParams, comparator); + Collections.sort(op.pathParams, comparator); + Collections.sort(op.queryParams, comparator); + Collections.sort(op.headerParams, comparator); + Collections.sort(op.implicitHeadersParams, comparator); + Collections.sort(op.formParams, comparator); + Collections.sort(op.cookieParams, comparator); + Collections.sort(op.requiredParams, comparator); + Collections.sort(op.optionalParams, comparator); + Collections.sort(op.requiredAndNotNullableParams, comparator); return op; } - private void addTestInstructions() { - if (GENERICHOST.equals(getLibrary())) { - additionalProperties.put("testInstructions", - "/* *********************************************************************************" + - "\n* Follow these manual steps to construct tests." + - "\n* This file will not be overwritten." + - "\n* *********************************************************************************" + - "\n* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly." + - "\n* Take care not to commit credentials to any repository." + - "\n*" + - "\n* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients." + - "\n* To mock the client, use the generic AddApiHttpClients." + - "\n* To mock the server, change the client's BaseAddress." + - "\n*" + - "\n* 3. Locate the test you want below" + - "\n* - remove the skip property from the Fact attribute" + - "\n* - set the value of any variables if necessary" + - "\n*" + - "\n* 4. Run the tests and ensure they work." + - "\n*" + - "\n*/"); - } - } - public void addSupportingFiles(final String clientPackageDir, final String packageFolder, final AtomicReference excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) { supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); @@ -912,8 +922,23 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs")); } - public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageFolder, - final AtomicReference excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) { + public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageDir, + final AtomicReference excludeTests, final String testPackageDir, final String testPackageName, final String modelPackageDir) { + supportingFiles.add(new SupportingFile("README.test.mustache", testPackageDir, "README.md")); + + supportingFiles.add(new SupportingFile("README.solution.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); + supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml")); + + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "docs" + File.separator + "scripts", "git_push.sh")); + supportingFiles.add(new SupportingFile("git_push.ps1.mustache", "docs" + File.separator + "scripts", "git_push.ps1")); + // TODO: supportingFiles.add(new SupportingFile("generate.ps1.mustache", "docs" + File.separator + "scripts", "generate.ps1")); + + supportingFiles.add(new SupportingFile("netcore_project.mustache", packageDir, packageName + ".csproj")); + supportingFiles.add(new SupportingFile("README.client.mustache", packageDir, "README.md")); + + // client directory supportingFiles.add(new SupportingFile("TokenProvider`1.mustache", clientPackageDir, "TokenProvider`1.cs")); supportingFiles.add(new SupportingFile("RateLimitProvider`1.mustache", clientPackageDir, "RateLimitProvider`1.cs")); supportingFiles.add(new SupportingFile("TokenContainer`1.mustache", clientPackageDir, "TokenContainer`1.cs")); @@ -922,23 +947,24 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("ApiResponse`1.mustache", clientPackageDir, "ApiResponse`1.cs")); supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); supportingFiles.add(new SupportingFile("HostConfiguration.mustache", clientPackageDir, "HostConfiguration.cs")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "docs" + File.separator + "scripts", "git_push.sh")); - supportingFiles.add(new SupportingFile("git_push.ps1.mustache", "docs" + File.separator + "scripts", "git_push.ps1")); - // TODO: supportingFiles.add(new SupportingFile("generate.ps1.mustache", "docs" + File.separator + "scripts", "generate.ps1")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); - supportingFiles.add(new SupportingFile("netcore_project.mustache", packageFolder, packageName + ".csproj")); - supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml")); - supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateJsonConverter.cs")); + supportingFiles.add(new SupportingFile("ApiFactory.mustache", clientPackageDir, "ApiFactory.cs")); + supportingFiles.add(new SupportingFile("DateTimeJsonConverter.mustache", clientPackageDir, "DateTimeJsonConverter.cs")); + supportingFiles.add(new SupportingFile("DateTimeNullableJsonConverter.mustache", clientPackageDir, "DateTimeNullableJsonConverter.cs")); supportingFiles.add(new SupportingFile("ApiResponseEventArgs.mustache", clientPackageDir, "ApiResponseEventArgs.cs")); - supportingFiles.add(new SupportingFile("IApi.mustache", clientPackageDir, getInterfacePrefix() + "Api.cs")); supportingFiles.add(new SupportingFile("JsonSerializerOptionsProvider.mustache", clientPackageDir, "JsonSerializerOptionsProvider.cs")); + supportingFiles.add(new SupportingFile("CookieContainer.mustache", clientPackageDir, "CookieContainer.cs")); + + supportingFiles.add(new SupportingFile("IApi.mustache", sourceFolder + File.separator + packageName + File.separator + apiPackage(), getInterfacePrefix() + "Api.cs")); + + // extensions + String extensionsFolder = sourceFolder + File.separator + packageName + File.separator + "Extensions"; + supportingFiles.add(new SupportingFile("IHttpClientBuilderExtensions.mustache", extensionsFolder, "IHttpClientBuilderExtensions.cs")); + supportingFiles.add(new SupportingFile("IHostBuilderExtensions.mustache", extensionsFolder, "IHostBuilderExtensions.cs")); + supportingFiles.add(new SupportingFile("IServiceCollectionExtensions.mustache", extensionsFolder, "IServiceCollectionExtensions.cs")); String apiTestFolder = testFolder + File.separator + testPackageName() + File.separator + apiPackage(); - if (Boolean.FALSE.equals(excludeTests.get())) { - supportingFiles.add(new SupportingFile("netcore_testproject.mustache", testPackageFolder, testPackageName + ".csproj")); + supportingFiles.add(new SupportingFile("netcore_testproject.mustache", testPackageDir, testPackageName + ".csproj")); supportingFiles.add(new SupportingFile("DependencyInjectionTests.mustache", apiTestFolder, "DependencyInjectionTests.cs")); // do not overwrite test file that already exists @@ -1409,7 +1435,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { * Check modules\openapi-generator\src\test\resources\3_0\java\petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml * Without this method, property petType in GrandparentAnimal will not make it through ParentPet and into ChildCat */ - private void EnsureInheritedPropertiesArePresent(CodegenModel derivedModel) { + private void ensureInheritedPropertiesArePresent(CodegenModel derivedModel) { // every c# generator should definitely want this, or we should fix the issue // still, lets avoid breaking changes :( if (Boolean.FALSE.equals(GENERICHOST.equals(getLibrary()))){ @@ -1429,7 +1455,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } } - EnsureInheritedPropertiesArePresent(derivedModel.parentModel); + ensureInheritedPropertiesArePresent(derivedModel.parentModel); } /** @@ -1466,12 +1492,46 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { }); } - EnsureInheritedPropertiesArePresent(cm); + ensureInheritedPropertiesArePresent(cm); + + for (CodegenProperty property : cm.allVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.vars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.readWriteVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.optionalVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.parentVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.requiredVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.readOnlyVars){ + fixInvalidPropertyName(cm, property); + } + for (CodegenProperty property : cm.nonNullableVars){ + fixInvalidPropertyName(cm, property); + } } return objs; } + private void fixInvalidPropertyName(CodegenModel model, CodegenProperty property){ + // TODO: remove once https://github.com/OpenAPITools/openapi-generator/pull/13681 is merged + if (property.name.equalsIgnoreCase(model.classname) || + reservedWords().contains(property.name) || + reservedWords().contains(camelize(sanitizeName(property.name), LOWERCASE_FIRST_LETTER))) { + property.name = property.name + "Property"; + } + } + /** * Removes properties from a model which are also defined in a composed class. * diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiException.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiException.mustache index c716cf25e99..c14c1010ffd 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiException.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiException.mustache @@ -6,7 +6,7 @@ {{/nrt}} using System; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// API Exception diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiFactory.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiFactory.mustache new file mode 100644 index 00000000000..6cb18d04ef2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiFactory.mustache @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// An IApiFactory interface + /// + {{>visibility}} interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : {{interfacePrefix}}{{apiPackage}}.IApi; + } + + /// + /// An ApiFactory + /// + {{>visibility}} 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 : {{interfacePrefix}}{{apiPackage}}.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiKeyToken.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiKeyToken.mustache index 25a751ad6bc..3bee0750d53 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiKeyToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiKeyToken.mustache @@ -6,12 +6,12 @@ {{/nrt}} using System; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A token constructed from an apiKey. /// - public class ApiKeyToken : TokenBase + {{>visibility}} class ApiKeyToken : TokenBase { private string _raw; @@ -20,22 +20,12 @@ namespace {{packageName}}.Client /// /// /// - /// + /// public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { _raw = $"{ prefix }{ value }"; } - /// - /// Places the token in the cookie. - /// - /// - /// - public virtual void UseInCookie(System.Net.Http.HttpRequestMessage request, string cookieName) - { - request.Headers.Add("Cookie", $"{ cookieName }=_raw"); - } - /// /// Places the token in the header. /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponseEventArgs.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponseEventArgs.mustache index 5ff16199326..a79086e63ad 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponseEventArgs.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponseEventArgs.mustache @@ -1,46 +1,57 @@ using System; using System.Net; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Useful for tracking server health. /// - public class ApiResponseEventArgs : EventArgs + {{>visibility}} class ApiResponseEventArgs : EventArgs { /// /// The time the request was sent. /// public DateTime RequestedAt { get; } + /// /// The time the response was received. /// public DateTime ReceivedAt { get; } + /// /// The HttpStatusCode received. /// public HttpStatusCode HttpStatus { get; } + /// /// The path requested. /// - public string Path { get; } + public string PathFormat { get; } + /// /// The elapsed time from request to response. /// public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + /// + /// The path + /// + public string Path { get; } + /// /// The event args used to track server health. /// /// /// /// + /// /// - public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string path) + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) { RequestedAt = requestedAt; ReceivedAt = receivedAt; HttpStatus = httpStatus; + PathFormat = pathFormat; Path = path; } } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponse`1.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponse`1.mustache index f37833790ed..7e2e1c8a78e 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponse`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiResponse`1.mustache @@ -8,12 +8,12 @@ using System; using System.Collections.Generic; using System.Net; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Provides a non-generic contract for the ApiResponse wrapper. /// - public interface IApiResponse + {{>visibility}} interface IApiResponse { /// /// The data type of @@ -30,6 +30,11 @@ namespace {{packageName}}.Client /// The raw content of this response /// string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } } /// @@ -37,13 +42,11 @@ namespace {{packageName}}.Client /// {{>visibility}} partial class ApiResponse : IApiResponse { - #region Properties - /// /// The deserialized content /// {{! .net 3.1 does not support unconstrained nullable T }} - public T{{#nrt}}{{^netcoreapp3.1}}?{{/netcoreapp3.1}}{{/nrt}} Content { get; set; } + public T{{#nrt}}{{^netcoreapp3.1}}?{{/netcoreapp3.1}}{{/nrt}} Content { get; internal set; } /// /// Gets or sets the status code (HTTP status code) @@ -79,7 +82,10 @@ namespace {{packageName}}.Client /// public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } - #endregion Properties + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; /// /// Construct the response using an HttpResponseMessage diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiTestsBase.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiTestsBase.mustache index 57dd3c7edee..ce4ef352123 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiTestsBase.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ApiTestsBase.mustache @@ -3,14 +3,15 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Extensions.Hosting; -using {{packageName}}.Client;{{#hasImport}} +using {{packageName}}.{{clientPackage}};{{#hasImport}} using {{packageName}}.{{modelPackage}};{{/hasImport}} +using {{packageName}}.Extensions; -{{{testInstructions}}} +{{>testInstructions}} -namespace {{packageName}}.Test.Api +namespace {{packageName}}.Test.{{apiPackage}} { /// /// Base class for API tests @@ -25,7 +26,7 @@ namespace {{packageName}}.Test.Api } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .Configure{{apiName}}((context, options) => + .Configure{{apiName}}((context, services, options) => { {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration[""], timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BasicToken.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BasicToken.mustache index a8a2b910a12..4cb7023f71e 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BasicToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BasicToken.mustache @@ -9,12 +9,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A token constructed from a username and password. /// - public class BasicToken : TokenBase + {{>visibility}} class BasicToken : TokenBase { private string _username; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BearerToken.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BearerToken.mustache index b6062bfc242..b0fc0a5d2eb 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BearerToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/BearerToken.mustache @@ -9,12 +9,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A token constructed from a token from a bearer token. /// - public class BearerToken : TokenBase + {{>visibility}} class BearerToken : TokenBase { private string _raw; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ClientUtils.mustache index 572565262e5..2c200d418af 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ClientUtils.mustache @@ -6,24 +6,17 @@ using System; using System.IO; using System.Linq; -using System.Net.Http; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}} -using Polly.Timeout; -using Polly.Extensions.Http; -using Polly;{{/supportsRetry}} -using {{packageName}}.Api;{{#useCompareNetObjects}} +using System.Text.RegularExpressions;{{#useCompareNetObjects}} using KellermanSoftware.CompareNetObjects;{{/useCompareNetObjects}} -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Utility functions providing some benefit to API client consumers. /// - public static class ClientUtils + {{>visibility}} static class ClientUtils { {{#useCompareNetObjects}} /// @@ -278,146 +271,5 @@ namespace {{packageName}}.Client /// The format to use for DateTime serialization /// public const string ISO8601_DATETIME_FORMAT = "o"; - - {{^hasAuthMethods}} - /// - /// Add the api to your host builder. - /// - /// - /// - public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder) - { - builder.ConfigureServices((context, services) => - { - HostConfiguration config = new HostConfiguration(services); - - Add{{apiName}}(services, config); - }); - - return builder; - } - - {{/hasAuthMethods}} - /// - /// Add the api to your host builder. - /// - /// - /// - public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder, Action options) - { - builder.ConfigureServices((context, services) => - { - HostConfiguration config = new HostConfiguration(services); - - options(context, config); - - Add{{apiName}}(services, config); - }); - - return builder; - } - - {{^hasAuthMethods}} - /// - /// Add the api to your host builder. - /// - /// - /// - public static void Add{{apiName}}(this IServiceCollection services) - { - HostConfiguration config = new HostConfiguration(services); - Add{{apiName}}(services, config); - } - - {{/hasAuthMethods}} - /// - /// Add the api to your host builder. - /// - /// - /// - public static void Add{{apiName}}(this IServiceCollection services, Action options) - { - HostConfiguration config = new HostConfiguration(services); - options(config); - Add{{apiName}}(services, config); - } - - private static void Add{{apiName}}(IServiceCollection services, HostConfiguration host) - { - if (!host.HttpClientsAdded) - host.Add{{apiName}}HttpClients(); - - // 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))); - } - } - }{{#supportsRetry}} - - /// - /// 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 circiut 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);{{/supportsRetry}} } } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/CookieContainer.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/CookieContainer.mustache new file mode 100644 index 00000000000..f96d4fb418f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/CookieContainer.mustache @@ -0,0 +1,22 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Linq; +using System.Collections.Generic; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A class containing a CookieContainer + /// + {{>visibility}} 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/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeFormats.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeFormats.mustache new file mode 100644 index 00000000000..4a24ef29b6e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeFormats.mustache @@ -0,0 +1,16 @@ + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OpenAPIDateConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeJsonConverter.mustache similarity index 55% rename from modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OpenAPIDateConverter.mustache rename to modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeJsonConverter.mustache index 144ac7328ac..bdf2b8c1cc8 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OpenAPIDateConverter.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeJsonConverter.mustache @@ -4,14 +4,18 @@ using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// 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 OpenAPIDateJsonConverter : JsonConverter + {{>visibility}} class DateTimeJsonConverter : JsonConverter { + public static readonly string[] FORMATS = { +{{>DateTimeFormats}} + }; + /// /// Returns a DateTime from the Json object /// @@ -19,8 +23,18 @@ namespace {{packageName}}.Client /// /// /// - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => - DateTime.ParseExact(reader.GetString(){{nrt!}}, "yyyy-MM-dd", CultureInfo.InvariantCulture); + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + 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 @@ -29,6 +43,6 @@ namespace {{packageName}}.Client /// /// public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => - writer.WriteStringValue(dateTimeValue.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); + writer.WriteStringValue(dateTimeValue.ToString(FORMATS[0], CultureInfo.InvariantCulture)); } } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeNullableJsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeNullableJsonConverter.mustache new file mode 100644 index 00000000000..224dd044c3f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DateTimeNullableJsonConverter.mustache @@ -0,0 +1,53 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// 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 + /// + {{>visibility}} class DateTimeNullableJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { +{{>DateTimeFormats}} + }; + + /// + /// 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(){{nrt!}}; + + 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(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DefaultApis.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DefaultApis.mustache new file mode 100644 index 00000000000..4729d92303f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DefaultApis.mustache @@ -0,0 +1 @@ +{{#apiInfo}}{{#apis}}{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DependencyInjectionTests.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DependencyInjectionTests.mustache index ac4a4d8e2d1..57d3cc86705 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DependencyInjectionTests.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/DependencyInjectionTests.mustache @@ -4,11 +4,12 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Security.Cryptography; -using {{packageName}}.Client; -using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{clientPackage}}; +using {{packageName}}.{{interfacePrefix}}{{apiPackage}}; +using {{packageName}}.Extensions; using Xunit; -namespace {{packageName}}.Test.Api +namespace {{packageName}}.Test.{{apiPackage}} { /// /// Tests the dependency injection. @@ -16,7 +17,7 @@ namespace {{packageName}}.Test.Api public class DependencyInjectionTest { private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, services, options) => { {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -37,7 +38,7 @@ namespace {{packageName}}.Test.Api .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, services, options) => { {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -113,7 +114,7 @@ namespace {{packageName}}.Test.Api [Fact] public void ConfigureApiWithAClientTest() { - {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} {{/-last}}{{/apis}}{{/apiInfo}} @@ -125,7 +126,7 @@ namespace {{packageName}}.Test.Api [Fact] public void ConfigureApiWithoutAClientTest() { - {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} {{/-last}}{{/apis}}{{/apiInfo}} @@ -137,7 +138,7 @@ namespace {{packageName}}.Test.Api [Fact] public void AddApiWithAClientTest() { - {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingAddWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingAddWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} {{/-last}}{{/apis}}{{/apiInfo}} @@ -149,7 +150,7 @@ namespace {{packageName}}.Test.Api [Fact] public void AddApiWithoutAClientTest() { - {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingAddWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingAddWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} {{/-last}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HostConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HostConfiguration.mustache index e74707baa81..4c6114f9f1c 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HostConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HostConfiguration.mustache @@ -10,18 +10,22 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Net.Http; using Microsoft.Extensions.DependencyInjection; -using {{packageName}}.Api; -using {{packageName}}.Model; +using {{packageName}}.{{modelPackage}}; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Provides hosting configuration for {{packageName}} /// - public class HostConfiguration + {{>visibility}} class HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} { private readonly IServiceCollection _services; - private JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); internal bool HttpClientsAdded { get; private set; } @@ -33,30 +37,22 @@ namespace {{packageName}}.Client { _services = services; _jsonOptions.Converters.Add(new JsonStringEnumConverter()); - _jsonOptions.Converters.Add(new OpenAPIDateJsonConverter()); -{{#models}} -{{#model}} -{{^isEnum}} -{{#allOf}} -{{#-first}} + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + {{#models}} + {{#model}} + {{#isEnum}} + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}Converter()); + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableConverter()); + {{/isEnum}} + {{^isEnum}} _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); -{{/-first}} -{{/allOf}} -{{#anyOf}} -{{#-first}} - _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); -{{/-first}} -{{/anyOf}} -{{#oneOf}} -{{#-first}} - _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); -{{/-first}} -{{/oneOf}} -{{/isEnum}} -{{/model}} -{{/models}} - _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions));{{#apiInfo}}{{#apis}} - _services.AddSingleton<{{interfacePrefix}}{{classname}}, {{classname}}>();{{/apis}}{{/apiInfo}} + {{/isEnum}} + {{/model}} + {{/models}} + _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); + _services.AddSingleton();{{#apiInfo}}{{#apis}} + _services.AddTransient();{{/apis}}{{/apiInfo}} } /// @@ -65,17 +61,16 @@ namespace {{packageName}}.Client /// /// /// - public HostConfiguration Add{{apiName}}HttpClients<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}> + public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> Add{{apiName}}HttpClients ( - Action{{nrt?}} client = null, Action{{nrt?}} builder = null){{#apis}} - where T{{classname}} : class, {{interfacePrefix}}{{classname}}{{/apis}} + Action{{nrt?}} client = null, Action{{nrt?}} builder = null) { if (client == null) client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); List builders = new List(); - - {{#apis}}builders.Add(_services.AddHttpClient<{{interfacePrefix}}{{classname}}, T{{classname}}>(client)); + + {{#apiInfo}}{{#apis}}builders.Add(_services.AddHttpClient<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}, T{{classname}}>(client)); {{/apis}}{{/apiInfo}} if (builder != null) foreach (IHttpClientBuilder instance in builders) @@ -86,25 +81,12 @@ namespace {{packageName}}.Client return this; } - /// - /// Configures the HttpClients. - /// - /// - /// - /// - public HostConfiguration Add{{apiName}}HttpClients(Action{{nrt?}} client = null, Action{{nrt?}} builder = null) - { - Add{{apiName}}HttpClients<{{#apiInfo}}{{#apis}}{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(client, builder); - - return this; - } - /// /// Configures the JsonSerializerSettings /// /// /// - public HostConfiguration ConfigureJsonOptions(Action options) + public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> ConfigureJsonOptions(Action options) { options(_jsonOptions); @@ -117,7 +99,7 @@ namespace {{packageName}}.Client /// /// /// - public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> AddTokens(TTokenBase token) where TTokenBase : TokenBase { return AddTokens(new TTokenBase[]{ token }); } @@ -128,7 +110,7 @@ namespace {{packageName}}.Client /// /// /// - public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> AddTokens(IEnumerable tokens) where TTokenBase : TokenBase { TokenContainer container = new TokenContainer(tokens); _services.AddSingleton(services => container); @@ -142,7 +124,7 @@ namespace {{packageName}}.Client /// /// /// - public HostConfiguration UseProvider() + public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> UseProvider() where TTokenProvider : TokenProvider where TTokenBase : TokenBase { diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningConfiguration.mustache index 4e17cf240ef..ed86b4967d1 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningConfiguration.mustache @@ -13,12 +13,12 @@ using System.Security.Cryptography; using System.Text; using System.Web; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Class for HttpSigning auth related parameter and methods /// - public class HttpSigningConfiguration + {{>visibility}} class HttpSigningConfiguration { #region /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningToken.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningToken.mustache index 224714027cc..353ce04fcac 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/HttpSigningToken.mustache @@ -9,12 +9,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A token constructed from an HttpSigningConfiguration /// - public class HttpSignatureToken : TokenBase + {{>visibility}} class HttpSignatureToken : TokenBase { private HttpSigningConfiguration _configuration; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IApi.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IApi.mustache index 019132830fc..0adffa75098 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IApi.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IApi.mustache @@ -1,21 +1,15 @@ using System.Net.Http; -namespace {{packageName}}.Client +namespace {{packageName}}.{{interfacePrefix}}{{apiPackage}} { /// /// Any Api client /// - public interface {{interfacePrefix}}Api + {{>visibility}} interface {{interfacePrefix}}Api { /// /// The HttpClient /// HttpClient HttpClient { get; } - - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - event ClientUtils.EventHandler{{nrt?}} ApiResponded; } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHostBuilderExtensions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHostBuilderExtensions.mustache new file mode 100644 index 00000000000..2c21e5be31c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHostBuilderExtensions.mustache @@ -0,0 +1,81 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using {{packageName}}.{{clientPackage}}; +using {{packageName}}.{{apiPackage}}; + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + {{>visibility}} static class IHostBuilderExtensions + { + {{^hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder Configure{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IHostBuilder builder) + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} + { + builder.ConfigureServices((context, services) => + { + HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> config = new HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(services); + + IServiceCollectionExtensions.Add{{apiName}}(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder) + => Configure{{apiName}}<{{>DefaultApis}}>(builder); + + {{/hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder Configure{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IHostBuilder builder, Action> options) + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} + { + builder.ConfigureServices((context, services) => + { + HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> config = new HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(services); + + options(context, services, config); + + IServiceCollectionExtensions.Add{{apiName}}(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder, ActionDefaultApis}}>> options) + => Configure{{apiName}}<{{>DefaultApis}}>(builder, options); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHttpClientBuilderExtensions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHttpClientBuilderExtensions.mustache new file mode 100644 index 00000000000..31e63690868 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IHttpClientBuilderExtensions.mustache @@ -0,0 +1,75 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}} +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly;{{/supportsRetry}} + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + {{>visibility}} static class IHttpClientBuilderExtensions + { + {{#supportsRetry}} + /// + /// 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 circiut 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); + {{/supportsRetry}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IServiceCollectionExtensions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IServiceCollectionExtensions.mustache new file mode 100644 index 00000000000..f1f4be90af1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/IServiceCollectionExtensions.mustache @@ -0,0 +1,109 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{clientPackage}}; +using {{packageName}}.{{apiPackage}}; + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + {{>visibility}} static class IServiceCollectionExtensions + { + {{^hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + /// + public static void Add{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IServiceCollection services) + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} + { + HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> config = new HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(services); + Add{{apiName}}(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void Add{{apiName}}(this IServiceCollection services) + { + HostConfiguration<{{>DefaultApis}}> config = new HostConfiguration<{{>DefaultApis}}>(services); + Add{{apiName}}(services, config); + } + + {{/hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + /// + public static void Add{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IServiceCollection services, Action> options) + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} + { + HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> config = new HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(services); + options(config); + Add{{apiName}}(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void Add{{apiName}}(this IServiceCollection services, ActionDefaultApis}}>> options) + { + HostConfiguration<{{>DefaultApis}}> config = new HostConfiguration<{{>DefaultApis}}>(services); + options(config); + Add{{apiName}}(services, config); + } + + internal static void Add{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(IServiceCollection services, HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> host) + {{#apiInfo}} + {{#apis}} + where T{{classname}} : class, {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} + {{/apis}} + {{/apiInfo}} + { + if (!host.HttpClientsAdded) + host.Add{{apiName}}HttpClients(); + + 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/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsIEquatable.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsIEquatable.mustache new file mode 100644 index 00000000000..25f679727af --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsIEquatable.mustache @@ -0,0 +1,3 @@ +{{#readOnlyVars}} +{{#-first}} +{{#parent}}, {{/parent}}{{^parent}} : {{/parent}}IEquatable<{{classname}}{{nrt?}}>{{/-first}}{{/readOnlyVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsValidatable.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsValidatable.mustache new file mode 100644 index 00000000000..546971159ec --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ImplementsValidatable.mustache @@ -0,0 +1,4 @@ +{{#validatable}} +{{^parent}} +{{^readOnlyVars}} + : {{/readOnlyVars}}{{/parent}}{{#parent}}{{^readOnlyVars}}, {{/readOnlyVars}}{{/parent}}{{^parent}}{{#readOnlyVars}}{{#-first}}, {{/-first}}{{/readOnlyVars}}{{/parent}}IValidatableObject{{/validatable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonConverter.mustache index 0a0f7540cae..00de10d513b 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonConverter.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonConverter.mustache @@ -1,15 +1,8 @@ /// /// A Json converter for type {{classname}} /// - public class {{classname}}JsonConverter : JsonConverter<{{classname}}> + {{>visibility}} class {{classname}}JsonConverter : JsonConverter<{{classname}}> { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof({{classname}}).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -22,9 +15,11 @@ { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + {{#composedSchemas.anyOf}} Utf8JsonReader {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader = reader; bool {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Deserialized = Client.ClientUtils.TryDeserialize<{{{dataType}}}>(ref {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader, options, out {{{dataType}}}{{^isBoolean}}{{nrt?}}{{/isBoolean}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}); @@ -38,20 +33,23 @@ {{#composedSchemas.allOf}} {{^isInherited}} Utf8JsonReader {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader = reader; - bool {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Deserialized = Client.ClientUtils.TryDeserialize<{{{dataType}}}>(ref {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader, options, out {{{dataType}}}{{^isBoolean}}{{nrt?}}{{/isBoolean}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}); + bool {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Deserialized = Client.ClientUtils.TryDeserialize<{{{dataType}}}>(ref reader, options, out {{{dataType}}}{{^isBoolean}}{{nrt?}}{{/isBoolean}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}); {{/isInherited}} {{/composedSchemas.allOf}} {{#allVars}} - {{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = default; + {{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{#isEnum}}{{#isNullable}}?{{/isNullable}}{{/isEnum}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = default; {{/allVars}} while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string{{nrt?}} propertyName = reader.GetString(); reader.Read(); @@ -61,48 +59,92 @@ {{#allVars}} case "{{baseName}}": {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetString(); + {{/isUuid}} + {{/isEnum}} + {{/isMap}} {{/isString}} {{#isBoolean}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetBoolean(); {{/isBoolean}} - {{#isDecimal}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDecimal(); - {{/isDecimal}} {{#isNumeric}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt32(); - {{/isNumeric}} - {{#isLong}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt64(); - {{/isLong}} + {{^isEnum}} {{#isDouble}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDouble(); {{/isDouble}} + {{#isDecimal}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDecimal(); + {{/isDecimal}} + {{#isFloat}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = (float)reader.GetDouble(); + {{/isFloat}} + {{#isLong}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt64(); + {{/isLong}} + {{^isLong}} + {{^isFloat}} + {{^isDecimal}} + {{^isDouble}} + {{#isNullable}} + if (reader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt32(); + {{/isNullable}} + {{^isNullable}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt32(); + {{/isNullable}} + {{/isDouble}} + {{/isDecimal}} + {{/isFloat}} + {{/isLong}} + {{/isEnum}} + {{/isNumeric}} {{#isDate}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDateTime(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize(ref reader, options); {{/isDate}} {{#isDateTime}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDateTime(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize(ref reader, options); {{/isDateTime}} + {{#isEnum}} + {{^isMap}} + {{#isNumeric}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}) reader.GetInt32(); + {{/isNumeric}} + {{^isNumeric}} + string {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = reader.GetString(); + {{^isInnerEnum}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{{datatypeWithEnum}}}Converter.FromString{{#isNullable}}OrDefault{{/isNullable}}({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + {{/isInnerEnum}} + {{#isInnerEnum}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{classname}}.{{{datatypeWithEnum}}}FromString({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetGuid(); + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} {{^isString}} {{^isBoolean}} - {{^isDecimal}} {{^isNumeric}} - {{^isLong}} - {{^isDouble}} {{^isDate}} {{^isDateTime}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref reader, options); {{/isDateTime}} {{/isDate}} - {{/isDouble}} - {{/isLong}} {{/isNumeric}} - {{/isDecimal}} {{/isBoolean}} {{/isString}} + {{/isEnum}} + {{/isUuid}} break; {{/allVars}} + default: + break; } } } @@ -127,5 +169,95 @@ /// /// /// - public override void Write(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + {{#allVars}} + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{/isNullable}} + {{/isBoolean}} + {{#isNumeric}} + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) + writer.WriteNumber("{{baseName}}", (int){{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + writer.WriteNumber("{{baseName}}", (int){{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{/isNullable}} + {{/isNumeric}} + {{#isDate}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, options); + {{/isDate}} + {{#isDateTime}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, options); + {{/isDateTime}} + {{#isEnum}} + {{^isMap}} + {{^isNumeric}} + {{#isInnerEnum}} + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + {{/isInnerEnum}} + {{^isInnerEnum}} + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} == null) + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{{datatypeWithEnum}}}Converter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{#isNullable}}.Value{{/isNullable}}); + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue != null) + writer.Write{{#allowableValues}}{{#enumVars}}{{#-first}}{{#isString}}String{{/isString}}{{^isString}}Number{{/isString}}{{/-first}}{{/enumVars}}{{/allowableValues}}("{{baseName}}", {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, options); + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + {{/allVars}} + + writer.WriteEndObject(); + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonSerializerOptionsProvider.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonSerializerOptionsProvider.mustache index 4b28944a2ae..93f8054031b 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonSerializerOptionsProvider.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/JsonSerializerOptionsProvider.mustache @@ -6,12 +6,12 @@ {{/nrt}} using System.Text.Json; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// Provides the JsonSerializerOptions /// - public class JsonSerializerOptionsProvider + {{>visibility}} class JsonSerializerOptionsProvider { /// /// the JsonSerializerOptions diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelBaseSignature.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelBaseSignature.mustache new file mode 100644 index 00000000000..ddc5ecaead3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelBaseSignature.mustache @@ -0,0 +1 @@ +{{#parentModel.composedSchemas.allOf}}{{^isInherited}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/isInherited}}{{/parentModel.composedSchemas.allOf}}{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{parent}}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{#isInherited}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} {{/isInherited}}{{/allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelSignature.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelSignature.mustache new file mode 100644 index 00000000000..1cc9190e969 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/ModelSignature.mustache @@ -0,0 +1 @@ +{{#model.allVars}}{{>PropertyDataType}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#defaultValue}} = {{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/defaultValue}}{{^defaultValue}}{{#isNullable}} = default{{/isNullable}}{{/defaultValue}} {{/model.allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OAuthToken.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OAuthToken.mustache index b5410ea0756..f450c3d092b 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OAuthToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OAuthToken.mustache @@ -9,12 +9,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A token constructed with OAuth. /// - public class OAuthToken : TokenBase + {{>visibility}} class OAuthToken : TokenBase { private string _raw; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationOrDefault.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationOrDefault.mustache new file mode 100644 index 00000000000..01a2d1daf10 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationOrDefault.mustache @@ -0,0 +1,24 @@ + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// <> + public async Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}OrDefaultAsync({{>OperationSignature}}) + { + ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>{{nrt?}} result = null; + try + { + result = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + } + + return result != null && result.IsSuccessStatusCode + ? result.Content + : null; + } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationSignature.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationSignature.mustache new file mode 100644 index 00000000000..64eabc543b3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/OperationSignature.mustache @@ -0,0 +1 @@ +{{#lambda.joinWithComma}}{{#allParams}}{{^notRequiredOrIsNullable}}{{#lambda.required}}{{{dataType}}}{{/lambda.required}}{{/notRequiredOrIsNullable}}{{#notRequiredOrIsNullable}}{{#lambda.optional}}{{{dataType}}}{{/lambda.optional}}{{/notRequiredOrIsNullable}} {{paramName}}{{^requiredAndNotNullable}} = null{{/requiredAndNotNullable}} {{/allParams}}System.Threading.CancellationToken? cancellationToken = null{{/lambda.joinWithComma}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/PropertyDataType.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/PropertyDataType.mustache new file mode 100644 index 00000000000..8ab7a12c805 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/PropertyDataType.mustache @@ -0,0 +1 @@ +{{#nrt}}{{#isNullable}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/isNullable}}{{^isNullable}}{{{datatypeWithEnum}}}{{/isNullable}}{{/nrt}}{{^nrt}}{{#isNullable}}{{#vendorExtensions.x-csharp-value-type}}{{{datatypeWithEnum}}}?{{/vendorExtensions.x-csharp-value-type}}{{^vendorExtensions.x-csharp-value-type}}{{{datatypeWithEnum}}}{{/vendorExtensions.x-csharp-value-type}}{{/isNullable}}{{^isNullable}}{{{datatypeWithEnum}}}{{/isNullable}}{{/nrt}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.client.mustache similarity index 96% rename from modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.mustache rename to modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.client.mustache index e76936568a7..f3cae79361a 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.client.mustache @@ -102,6 +102,9 @@ namespace YourProject 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 {{packageName}}.Rest.DefaultApi. + Or provide your own class by using the generic Configure{{apiName}} method. ## Dependencies @@ -109,9 +112,7 @@ namespace YourProject - [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{{#supportsRetry}} - [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later -- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later{{/supportsRetry}} -- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.1 or later -- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.7.0 or later{{#useCompareNetObjects}} +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later{{/supportsRetry}}{{#useCompareNetObjects}} - [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later{{/useCompareNetObjects}}{{#validatable}} - [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later{{/validatable}}{{#apiDocs}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.solution.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.solution.mustache new file mode 100644 index 00000000000..f9c1c7f7462 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.solution.mustache @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/README.test.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/RateLimitProvider`1.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/RateLimitProvider`1.mustache index 944c0061f5a..03a117341fb 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/RateLimitProvider`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/RateLimitProvider`1.mustache @@ -11,13 +11,13 @@ using System.Linq; using System.Threading; using System.Threading.Tasks;{{/netStandard}} -namespace {{packageName}}.Client {{^netStandard}} +namespace {{packageName}}.{{clientPackage}} {{^netStandard}} { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. /// /// - public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + {{>visibility}} class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { internal Channel AvailableTokens { get; } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenBase.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenBase.mustache index fd720d1dcea..2373db173cd 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenBase.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenBase.mustache @@ -6,12 +6,12 @@ {{/nrt}} using System; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// The base for all tokens. /// - public abstract class TokenBase + {{>visibility}} abstract class TokenBase { private DateTime _nextAvailable = DateTime.UtcNow; private object _nextAvailableLock = new object(); diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenContainer`1.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenContainer`1.mustache index 9d742241daf..3e8f1b15dd0 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenContainer`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenContainer`1.mustache @@ -7,13 +7,13 @@ using System.Linq; using System.Collections.Generic; -namespace {{packageName}}.Client +namespace {{packageName}}.{{clientPackage}} { /// /// A container for a collection of tokens. /// /// - public sealed class TokenContainer where TTokenBase : TokenBase + {{>visibility}} sealed class TokenContainer where TTokenBase : TokenBase { /// /// The collection of tokens diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenProvider`1.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenProvider`1.mustache index cc8bbd72e42..26130f4b39b 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenProvider`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/TokenProvider`1.mustache @@ -7,14 +7,14 @@ using System; using System.Linq; using System.Collections.Generic; -using {{packageName}}.Client; +using {{packageName}}.{{clientPackage}}; namespace {{packageName}} { /// /// A class which will provide tokens. /// - public abstract class TokenProvider where TTokenBase : TokenBase + {{>visibility}} abstract class TokenProvider where TTokenBase : TokenBase { /// /// The array of tokens. diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api.mustache index 439b19cad35..8753cadab33 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api.mustache @@ -12,16 +12,17 @@ using Microsoft.Extensions.Logging; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; -using {{packageName}}.Client; +using {{packageName}}.{{clientPackage}}; {{#hasImport}} using {{packageName}}.{{modelPackage}}; {{/hasImport}} -namespace {{packageName}}.{{apiPackage}} +namespace {{packageName}}.{{interfacePrefix}}{{apiPackage}} { {{#operations}} /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// {{>visibility}} interface {{interfacePrefix}}{{classname}} : IApi { @@ -38,7 +39,7 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} /// Cancellation Token to cancel the request. /// Task<ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>> - Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null); + Task> {{operationId}}WithHttpInfoAsync({{>OperationSignature}}); /// /// {{summary}} @@ -52,7 +53,7 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} /// Cancellation Token to cancel the request. /// Task of ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}> - Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}Async({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null);{{#nrt}} + Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}> {{operationId}}Async({{>OperationSignature}});{{#nrt}} /// /// {{summary}} @@ -65,26 +66,23 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} /// Cancellation Token to cancel the request. /// Task of ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}?> - Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}OrDefaultAsync({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null); + Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}OrDefaultAsync({{>OperationSignature}});{{/nrt}} + {{^-last}} - {{/nrt}}{{^-last}} {{/-last}} {{/operation}} } +} +namespace {{packageName}}.{{apiPackage}} +{ /// /// Represents a collection of functions to interact with the API endpoints /// - {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler{{nrt?}} ApiResponded; - /// /// The logger /// @@ -140,6 +138,15 @@ namespace {{packageName}}.{{apiPackage}} HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}} } + + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } {{#operation}} /// @@ -151,7 +158,7 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} /// Cancellation Token to cancel the request. /// <> - public async Task<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}Async({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null) + public async Task<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}> {{operationId}}Async({{>OperationSignature}}) { ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> result = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); @@ -160,66 +167,80 @@ namespace {{packageName}}.{{apiPackage}} #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'{{/returnTypeIsPrimitive}}{{/nrt}} throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); - return result.Content; + return result.Content{{#nrt}}{{#returnProperty}}{{#isPrimitiveType}}{{^isMap}}{{^isString}}.Value{{/isString}}{{/isMap}}{{/isPrimitiveType}}{{/returnProperty}}{{/nrt}}; } {{#nrt}} - /// - /// {{summary}} {{notes}} - /// - /// Thrown when fails to make API call - {{#allParams}} - /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} - {{/allParams}} - /// Cancellation Token to cancel the request. - /// <> - public async Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}OrDefaultAsync({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null) - { - ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>{{nrt?}} result = null; - try - { - result = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); - } - catch (Exception) - { - } - - return result != null && result.IsSuccessStatusCode - ? result.Content - : null; - } +{{>OperationOrDefault}} {{/nrt}} {{^nrt}} {{^returnTypeIsPrimitive}} - {{! Note that this method is a copy paste of above due to NRT complexities }} - /// - /// {{summary}} {{notes}} - /// - /// Thrown when fails to make API call - {{#allParams}} - /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} - {{/allParams}} - /// Cancellation Token to cancel the request. - /// <> - public async Task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> {{operationId}}OrDefaultAsync({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null) - { - ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>{{nrt?}} result = null; - try - { - result = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); - } - catch (Exception) - { - } - - return result != null && result.IsSuccessStatusCode - ? result.Content - : null; - } +{{>OperationOrDefault}} {{/returnTypeIsPrimitive}} {{/nrt}} + /// + /// Validates the request parameters + /// + {{#allParams}} + /// + {{/allParams}} + /// + protected virtual {{^allParams}}void{{/allParams}}{{#allParams}}{{#-first}}{{^-last}}({{/-last}}{{/-first}}{{#requiredAndNotNullable}}{{#lambda.required}}{{{dataType}}}{{/lambda.required}}{{^-last}}, {{/-last}}{{/requiredAndNotNullable}}{{^requiredAndNotNullable}}{{#lambda.optional}}{{{dataType}}}{{/lambda.optional}}{{^-last}}, {{/-last}}{{/requiredAndNotNullable}}{{#-last}}{{^-first}}){{/-first}}{{/-last}}{{/allParams}} On{{operationId}}({{#allParams}}{{#requiredAndNotNullable}}{{#lambda.required}}{{{dataType}}}{{/lambda.required}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredAndNotNullable}}{{^requiredAndNotNullable}}{{#lambda.optional}}{{{dataType}}}{{/lambda.optional}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredAndNotNullable}}{{/allParams}}) + { + {{#requiredAndNotNullableParams}} + {{#-first}} + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + {{/-first}} + {{#nrt}} + if ({{paramName}} == null) + throw new ArgumentNullException(nameof({{paramName}})); + + {{/nrt}} + {{^nrt}} + {{^vendorExtensions.x-csharp-value-type}} + if ({{paramName}} == null) + throw new ArgumentNullException(nameof({{paramName}})); + + {{/vendorExtensions.x-csharp-value-type}} + {{/nrt}} + {{#-last}} + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + {{/-last}} + {{/requiredAndNotNullableParams}} + return{{#allParams}} {{#-first}}{{^-last}}({{/-last}}{{/-first}}{{paramName}}{{^-last}},{{/-last}}{{#-last}}{{^-first}}){{/-first}}{{/-last}}{{/allParams}}; + } + + /// + /// Processes the server response + /// + /// + {{#allParams}} + /// + {{/allParams}} + protected virtual void After{{operationId}}({{#lambda.joinWithComma}}ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> apiResponse {{#allParams}}{{#requiredAndNotNullable}}{{#lambda.required}}{{{dataType}}}{{/lambda.required}} {{paramName}} {{/requiredAndNotNullable}}{{^requiredAndNotNullable}}{{#lambda.optional}}{{{dataType}}}{{/lambda.optional}} {{paramName}} {{/requiredAndNotNullable}}{{/allParams}}{{/lambda.joinWithComma}}) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + {{#allParams}} + /// + {{/allParams}} + protected virtual void OnError{{operationId}}({{#lambda.joinWithComma}}Exception exception string pathFormat string path {{#allParams}}{{#requiredAndNotNullable}}{{#lambda.required}}{{{dataType}}}{{/lambda.required}} {{paramName}} {{/requiredAndNotNullable}}{{^requiredAndNotNullable}}{{#lambda.optional}}{{{dataType}}}{{/lambda.optional}} {{paramName}} {{/requiredAndNotNullable}}{{/allParams}}{{/lambda.joinWithComma}}) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// {{summary}} {{notes}} /// @@ -229,33 +250,53 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} /// Cancellation Token to cancel the request. /// <> where T : - public async Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{^required}}{{{dataType}}} {{paramName}} = null{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken? cancellationToken = null) + public async Task> {{operationId}}WithHttpInfoAsync({{>OperationSignature}}) { + UriBuilder uriBuilder = new UriBuilder(); + try { - {{#hasRequiredParams}}#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'{{/hasRequiredParams}}{{#allParams}}{{#required}}{{#nrt}} + {{#allParams}}{{#-first}}{{#-last}}{{paramName}} = {{/-last}}{{^-last}}var validatedParameters = {{/-last}}{{/-first}}{{/allParams}}On{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#allParams}} + {{#-first}} + {{^-last}} + {{#allParams}} + {{paramName}} = validatedParameters.Item{{-index}}; + {{/allParams}} + {{/-last}} + {{/-first}} + {{/allParams}} - if ({{paramName}} == null) - throw new ArgumentNullException(nameof({{paramName}}));{{/nrt}}{{^nrt}}{{^vendorExtensions.x-csharp-value-type}} - - if ({{paramName}} == null) - throw new ArgumentNullException(nameof({{paramName}}));{{/vendorExtensions.x-csharp-value-type}}{{/nrt}}{{/required}}{{/allParams}}{{#hasRequiredParams}} - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - {{/hasRequiredParams}}using (HttpRequestMessage request = new HttpRequestMessage()) + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); + {{^servers}} uriBuilder.Host = HttpClient.BaseAddress{{nrt!}}.Host; uriBuilder.Port = HttpClient.BaseAddress{{nrt!}}.Port; uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "{{path}}";{{#pathParams}}{{#required}} - uriBuilder.Path = uriBuilder.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString()));{{/required}}{{^required}} + uriBuilder.Path = ClientUtils.CONTEXT_PATH + "{{path}}"; + {{/servers}} + {{#servers}} + {{#-first}} + var url = request.RequestUri = new Uri("{{url}}"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; + + {{/-first}} + {{/servers}} + {{#pathParams}} + {{#required}} + uriBuilder.Path = uriBuilder.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString()));{{/required}}{{^required}} if ({{paramName}} != null) uriBuilder.Path = uriBuilder.Path + $"/{ Uri.EscapeDataString({{paramName}}).ToString()) }"; - {{/required}}{{/pathParams}}{{#queryParams}}{{#-first}} + {{#-last}} + {{/-last}} + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#-first}} System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty);{{/-first}}{{/queryParams}}{{^queryParams}}{{#authMethods}}{{#isApiKey}}{{#isKeyInQuery}} System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty);{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}}{{/queryParams}}{{#queryParams}}{{#required}}{{#-first}} @@ -266,13 +307,23 @@ namespace {{packageName}}.{{apiPackage}} {{/-first}}{{/queryParams}}{{#queryParams}}{{^required}}if ({{paramName}} != null) parseQueryString["{{baseName}}"] = Uri.EscapeDataString({{paramName}}.ToString(){{nrt!}}); - {{/required}}{{#-last}}uriBuilder.Query = parseQueryString.ToString();{{/-last}}{{/queryParams}}{{#headerParams}}{{#required}} + {{/required}}{{#-last}}uriBuilder.Query = parseQueryString.ToString(); - request.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}}));{{/required}}{{^required}} + {{/-last}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + request.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}})); + {{/required}} + {{^required}} if ({{paramName}} != null) - request.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}}));{{/required}}{{/headerParams}}{{#formParams}}{{#-first}} + request.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}})); + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#-first}} MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; @@ -281,22 +332,39 @@ namespace {{packageName}}.{{apiPackage}} multipartContent.Add(new FormUrlEncodedContent(formParams));{{/-first}}{{^isFile}}{{#required}} - formParams.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}})));{{/required}}{{^required}} + formParams.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}))); + {{/required}} + {{^required}} if ({{paramName}} != null) - formParams.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}})));{{/required}}{{/isFile}}{{#isFile}}{{#required}} + formParams.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}))); - multipartContent.Add(new StreamContent({{paramName}}));{{/required}}{{^required}} + {{/required}} + {{/isFile}} + {{#isFile}} + {{#required}} + multipartContent.Add(new StreamContent({{paramName}})); + {{/required}} + {{^required}} if ({{paramName}} != null) - multipartContent.Add(new StreamContent({{paramName}}));{{/required}}{{/isFile}}{{/formParams}}{{#bodyParam}} + multipartContent.Add(new StreamContent({{paramName}})); + {{/required}} + {{/isFile}} + {{/formParams}} + {{#bodyParam}} request.Content = ({{paramName}} as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) - : request.Content = new StringContent(JsonSerializer.Serialize({{paramName}}, _jsonSerializerOptions));{{/bodyParam}}{{#authMethods}}{{#-first}} + : request.Content = new StringContent(JsonSerializer.Serialize({{paramName}}, _jsonSerializerOptions)); - List tokens = new List();{{/-first}}{{#isApiKey}} + {{/bodyParam}} + {{#authMethods}} + {{#-first}} + List tokens = new List(); + {{/-first}} + {{#isApiKey}} ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); tokens.Add(apiKey);{{#isKeyInHeader}} @@ -305,11 +373,7 @@ namespace {{packageName}}.{{apiPackage}} apiKey.UseInQuery(request, uriBuilder, parseQueryString, "{{keyParamName}}"); - uriBuilder.Query = parseQueryString.ToString();{{/isKeyInQuery}}{{#isKeyInCookie}} - - apiKey.UseInCookie(request, parseQueryString, "{{keyParamName}}"); - - uriBuilder.Query = parseQueryString.ToString();{{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}} + uriBuilder.Query = parseQueryString.ToString();{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}} {{! below line must be after any UseInQuery calls, but before using the HttpSignatureToken}} request.RequestUri = uriBuilder.Uri;{{#authMethods}}{{#isBasicBasic}} @@ -348,7 +412,7 @@ namespace {{packageName}}.{{apiPackage}} string{{nrt?}} contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType);{{/-first}}{{/consumes}}{{#produces}}{{#-first}} + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);{{/-first}}{{/consumes}}{{#produces}}{{#-first}} string[] accepts = new string[] { {{/-first}}{{/produces}} {{#produces}}"{{{mediaType}}}"{{^-last}}, @@ -359,35 +423,33 @@ namespace {{packageName}}.{{apiPackage}} if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - {{/-first}}{{/produces}}{{^netStandard}} + {{/-first}} + {{/produces}} + {{^netStandard}} + request.Method = HttpMethod.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}};{{/netStandard}}{{#netStandard}} request.Method = new HttpMethod("{{#lambda.uppercase}}{{httpMethod}}{{/lambda.uppercase}}");{{/netStandard}}{{! early standard versions do not have HttpMethod.Patch }} + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "{{path}}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync({{^netStandard}}{{^netcoreapp3.1}}cancellationToken.GetValueOrDefault(){{/netcoreapp3.1}}{{/netStandard}}).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "{{path}}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> apiResponse = new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) - apiResponse.Content = JsonSerializer.Deserialize<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}>(apiResponse.RawContent, _jsonSerializerOptions);{{#authMethods}} + { + apiResponse.Content = JsonSerializer.Deserialize<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}>(apiResponse.RawContent, _jsonSerializerOptions); + After{{operationId}}({{#lambda.joinWithComma}}apiResponse {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); + } + {{#authMethods}} else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) - token.BeginRateLimit();{{/authMethods}} + token.BeginRateLimit(); + {{/authMethods}} return apiResponse; } @@ -395,11 +457,10 @@ namespace {{packageName}}.{{apiPackage}} } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnError{{operationId}}({{#lambda.joinWithComma}}e "{{path}}" uriBuilder.Path {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); throw; } - }{{^-last}} - {{/-last}} + } {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api_test.mustache index b64731f81dd..b46a103b406 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/api_test.mustache @@ -4,25 +4,25 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using {{packageName}}.{{apiPackage}};{{#hasImport}} +using {{packageName}}.{{interfacePrefix}}{{apiPackage}};{{#hasImport}} using {{packageName}}.{{modelPackage}};{{/hasImport}} -{{{testInstructions}}} +{{>testInstructions}} -namespace {{packageName}}.Test.Api +namespace {{packageName}}.Test.{{apiPackage}} { /// /// Class for testing {{classname}} /// public sealed class {{classname}}Tests : ApiTestsBase { - private readonly {{interfacePrefix}}{{classname}} _instance; + private readonly {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} _instance; public {{classname}}Tests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + _instance = _host.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>(); } {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/model.mustache index d6e643a2feb..cd592f97867 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/model.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/model.mustache @@ -10,7 +10,9 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; +{{^useGenericHost}} using System.Runtime.Serialization; +{{/useGenericHost}} using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -26,23 +28,13 @@ using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; namespace {{packageName}}.{{modelPackage}} { -{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>modelGeneric}} +{{#isEnum}} +{{>modelEnum}} +{{/isEnum}} +{{^isEnum}} +{{>modelGeneric}} -{{#allOf}} -{{#-first}} {{>JsonConverter}} -{{/-first}} -{{/allOf}} -{{#anyOf}} -{{#-first}} -{{>JsonConverter}} -{{/-first}} -{{/anyOf}} -{{#oneOf}} -{{#-first}} -{{>JsonConverter}} -{{/-first}} -{{/oneOf}} {{/isEnum}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/modelGeneric.mustache index 1f18f91bce0..1df0e038eb4 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/modelGeneric.mustache @@ -1,7 +1,7 @@ /// /// {{description}}{{^description}}{{classname}}{{/description}} /// - {{>visibility}} partial class {{classname}} : {{#parent}}{{{.}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}{{^parentModel}}, IValidatableObject{{/parentModel}}{{/validatable}} + {{>visibility}} partial class {{classname}}{{#parent}} : {{{.}}}{{/parent}}{{>ImplementsIEquatable}}{{>ImplementsValidatable}} { {{#composedSchemas.oneOf}} /// @@ -17,21 +17,26 @@ /// {{/composedSchemas.anyOf}} {{#allVars}} - /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} {{/allVars}} - public {{classname}}({{#lambda.joinWithComma}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{#model.composedSchemas.allOf}}{{^isInherited}}{{{dataType}}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/isInherited}}{{/model.composedSchemas.allOf}}{{#model.composedSchemas.anyOf}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/model.composedSchemas.anyOf}}{{#model.allVars}}{{^compulsory}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/compulsory}}{{#compulsory}}{{{datatypeWithEnum}}}{{/compulsory}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#defaultValue}} = {{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/defaultValue}}{{^defaultValue}}{{^compulsory}} = default{{/compulsory}}{{/defaultValue}} {{/model.allVars}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{#parentModel.composedSchemas.allOf}}{{^isInherited}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/isInherited}}{{/parentModel.composedSchemas.allOf}}{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{parent}}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{#isInherited}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} {{/isInherited}}{{/allVars}}{{/lambda.joinWithComma}}){{/parent}} + [JsonConstructor] + {{#readWriteVars}}{{#-first}}public{{/-first}}{{/readWriteVars}}{{^readWriteVars}}internal{{/readWriteVars}} {{classname}}({{#lambda.joinWithComma}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{#model.composedSchemas.allOf}}{{^isInherited}}{{{dataType}}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/isInherited}}{{/model.composedSchemas.allOf}}{{#model.composedSchemas.anyOf}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/model.composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} { - {{#allVars}} - {{^isInherited}} - {{#required}} - {{^isNullable}} - if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} == null) - throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null."); + {{#nonNullableVars}} + {{#-first}} + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - {{/isNullable}} - {{/required}} - {{/isInherited}} - {{/allVars}} + {{/-first}} + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} == null) + throw new ArgumentNullException(nameof({{name}})); + + {{#-last}} + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + {{/-last}} + {{/nonNullableVars}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; {{#composedSchemas.allOf}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; @@ -60,21 +65,26 @@ /// {{/composedSchemas.anyOf}} {{#allVars}} - /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} {{/allVars}} - public {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.allOf}}{{^isInherited}}{{{dataType}}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/isInherited}}{{/composedSchemas.allOf}}{{#composedSchemas.anyOf}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/composedSchemas.anyOf}}{{#allVars}}{{^compulsory}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/compulsory}}{{#compulsory}}{{{datatypeWithEnum}}}{{/compulsory}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#defaultValue}} = {{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/defaultValue}}{{^defaultValue}}{{^compulsory}} = default{{/compulsory}}{{/defaultValue}} {{/allVars}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{#parentModel.composedSchemas.allOf}}{{^isInherited}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/isInherited}}{{/parentModel.composedSchemas.allOf}}{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{parent}}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{#isInherited}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} {{/isInherited}}{{/allVars}}{{/lambda.joinWithComma}}){{/parent}} + [JsonConstructor] + {{#readWriteVars}}{{#-first}}public{{/-first}}{{/readWriteVars}}{{^readWriteVars}}internal{{/readWriteVars}} {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.allOf}}{{^isInherited}}{{{dataType}}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/isInherited}}{{/composedSchemas.allOf}}{{#composedSchemas.anyOf}}{{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}} {{/composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} { - {{#allVars}} - {{^isInherited}} - {{#required}} - {{^isNullable}} + {{#nonNullableVars}} + {{#-first}} +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + {{/-first}} if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} == null) throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null."); - {{/isNullable}} - {{/required}} - {{/isInherited}} - {{/allVars}} + {{#-last}} +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + {{/-last}} + {{/nonNullableVars}} {{#composedSchemas.allOf}} {{^isInherited}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; @@ -115,7 +125,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{#isNullable}}{{#required}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/required}}{{/isNullable}}{{^isNullable}}{{^required}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/required}}{{/isNullable}}{{^isNullable}}{{#required}}{{{datatypeWithEnum}}}{{/required}}{{/isNullable}}{{#isNullable}}{{^required}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/required}}{{/isNullable}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + public {{>PropertyDataType}} {{name}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} {{/isEnum}} {{/vars}} @@ -127,7 +137,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + public {{{dataType}}}{{nrt?}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} {{/composedSchemas.anyOf}} {{#composedSchemas.oneOf}} @@ -138,7 +148,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{{dataType}}}{{#isNullable}}{{nrt?}}{{/isNullable}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + public {{{dataType}}}{{nrt?}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} {{/composedSchemas.oneOf}} {{#composedSchemas.allOf}} @@ -150,7 +160,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{{dataType}}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + public {{{dataType}}} {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} {{/isInherited}} {{/composedSchemas.allOf}} @@ -165,7 +175,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{^compulsory}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/compulsory}}{{#compulsory}}{{{datatypeWithEnum}}}{{/compulsory}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + public {{#isNullable}}{{#lambda.optional}}{{{datatypeWithEnum}}}{{/lambda.optional}}{{/isNullable}}{{^isNullable}}{{{datatypeWithEnum}}}{{/isNullable}} {{name}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} {{/isEnum}} {{/isInherited}} @@ -176,7 +186,7 @@ /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); {{/parentModel}} {{/isAdditionalPropertiesTrue}} @@ -202,6 +212,8 @@ sb.Append("}\n"); return sb.ToString(); } + {{#readOnlyVars}} + {{#-first}} /// /// Returns true if objects are equal @@ -230,29 +242,28 @@ {{/useCompareNetObjects}} {{^useCompareNetObjects}} if (input == null) - { return false; - } - return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} + + return {{#parent}}base.Equals(input) && {{/parent}}{{#readOnlyVars}}{{^isInherited}}{{^isContainer}} ( - this.{{name}} == input.{{name}} || + {{name}} == input.{{name}} || {{^vendorExtensions.x-is-value-type}} - (this.{{name}} != null && - this.{{name}}.Equals(input.{{name}})) + ({{name}} != null && + {{name}}.Equals(input.{{name}})) {{/vendorExtensions.x-is-value-type}} {{#vendorExtensions.x-is-value-type}} - this.{{name}}.Equals(input.{{name}}) + {{name}}.Equals(input.{{name}}) {{/vendorExtensions.x-is-value-type}} ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} ( - this.{{name}} == input.{{name}} || - {{^vendorExtensions.x-is-value-type}}this.{{name}} != null && + {{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}{{name}} != null && input.{{name}} != null && - {{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) - ){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{/vendorExtensions.x-is-value-type}}{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} {{#isAdditionalPropertiesTrue}} {{^parentModel}} - && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); + && (AdditionalProperties.Count == input.AdditionalProperties.Count && !AdditionalProperties.Except(input.AdditionalProperties).Any()); {{/parentModel}} {{/isAdditionalPropertiesTrue}} {{/useCompareNetObjects}} @@ -272,29 +283,29 @@ {{^parent}} int hashCode = 41; {{/parent}} - {{#vars}} - {{^vendorExtensions.x-is-value-type}} - if (this.{{name}} != null) - { - hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); - } - {{/vendorExtensions.x-is-value-type}} - {{#vendorExtensions.x-is-value-type}} - hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); - {{/vendorExtensions.x-is-value-type}} - {{/vars}} + {{#readOnlyVars}} + {{^isNullable}} + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/isNullable}} + {{/readOnlyVars}} + {{#readOnlyVars}} + {{#isNullable}} + + if ({{name}} != null) + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/isNullable}} + {{/readOnlyVars}} {{#isAdditionalPropertiesTrue}} {{^parentModel}} - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); {{/parentModel}} {{/isAdditionalPropertiesTrue}} + return hashCode; } } - + {{/-first}} + {{/readOnlyVars}} {{#validatable}} {{^parentModel}} {{>validatable}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/testInstructions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/testInstructions.mustache new file mode 100644 index 00000000000..7bf738e207c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/generichost/testInstructions.mustache @@ -0,0 +1,18 @@ +/* ********************************************************************************* +* 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. +* +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache index 514542d70e4..a12611e9cf0 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache @@ -29,10 +29,125 @@ /// Enum {{name}} for value: {{value}} /// {{#isString}} + {{^useGenericHost}} + {{! EnumMember not currently supported in System.Text.Json, use a converter instead }} [EnumMember(Value = "{{{value}}}")] + {{/useGenericHost}} {{/isString}} - {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + {{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} - }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}} + } + {{#useGenericHost}} + + public class {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}Converter : JsonConverter<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> + { + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} FromString(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value == {{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}}) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Could not convert value to type {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}: '{value}'"); + } + + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? FromStringOrDefault(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value == {{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}}) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + return null; + } + + public static {{#isString}}string{{/isString}}{{^isString}}int{{/isString}} ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} value) + { + {{^isString}} + return (int) value; + {{/isString}} + {{#isString}} + {{#allowableValues}} + {{#enumVars}} + if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}) + return "{{value}}"; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Value could not be handled: '{value}'"); + {{/isString}} + } + + /// + /// Returns a {{datatypeWithEnum}} from the Json object + /// + /// + /// + /// + /// + public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string{{nrt?}} rawValue = reader.GetString(); + + {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}Converter.FromString(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}, JsonSerializerOptions options) + { + writer.WriteStringValue({{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}.ToString()); + } + } + + public class {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableConverter : JsonConverter<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}?> + { + /// + /// Returns a {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} from the Json object + /// + /// + /// + /// + /// + public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string{{nrt?}} rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}Converter.FromString(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? {{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}, JsonSerializerOptions options) + { + writer.WriteStringValue({{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}?.ToString() ?? "null"); + } + } + {{/useGenericHost}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache index f879f022dae..f79a78178a0 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache @@ -17,12 +17,61 @@ /// /// Enum {{name}} for value: {{value}} /// + {{^useGenericHost}} {{#isString}} [EnumMember(Value = "{{{value}}}")] {{/isString}} - {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + {{/useGenericHost}} + {{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} } - {{/isContainer}} + {{#useGenericHost}} + + /// + /// Returns a {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + /// + /// + /// + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#isNullable}}?{{/isNullable}} {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}FromString(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value == {{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}}) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + {{#isNullable}} + return null; + {{/isNullable}} + {{^isNullable}} + throw new NotImplementedException($"Could not convert value to type {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}: '{value}'"); + {{/isNullable}} + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static {{#isString}}string{{/isString}}{{^isString}}int{{/isString}} {{datatypeWithEnum}}ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} value) + { + {{^isString}} + return (int) value; + {{/isString}} + {{#isString}} + {{#allowableValues}} + {{#enumVars}} + if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}) + return "{{value}}"; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Value could not be handled: '{value}'"); + {{/isString}} + } + {{/useGenericHost}} + {{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/model_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/model_test.mustache index b4aefe51005..347c2c35a25 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/model_test.mustache @@ -8,9 +8,11 @@ using System.IO; using System.Collections.Generic; using {{packageName}}.{{apiPackage}}; using {{packageName}}.{{modelPackage}}; -using {{packageName}}.Client; +using {{packageName}}.{{clientPackage}}; using System.Reflection; +{{^useGenericHost}} using Newtonsoft.Json; +{{/useGenericHost}} {{#models}} {{#model}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.additions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.additions.mustache new file mode 100644 index 00000000000..8c6f3ad52d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.additions.mustache @@ -0,0 +1 @@ +{{! if needed users can add this file to their templates folder to append to the csproj }} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache index 3befcffaf4a..6c9744625ea 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache @@ -35,14 +35,14 @@ {{/useRestSharp}} {{#useGenericHost}} - - + + {{#supportsRetry}} - + {{/supportsRetry}} {{/useGenericHost}} {{#supportsRetry}} - + {{/supportsRetry}} {{#validatable}} @@ -61,4 +61,4 @@ {{/net48}} - +{{>netcore_project.additions}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.additions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.additions.mustache new file mode 100644 index 00000000000..8c6f3ad52d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.additions.mustache @@ -0,0 +1 @@ +{{! if needed users can add this file to their templates folder to append to the csproj }} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.mustache index d4b2048ae54..078005bc236 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_testproject.mustache @@ -9,13 +9,12 @@ - - - + + + - - +{{>netcore_testproject.additions}} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index a68e9179c81..06b106b96d3 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -16,5 +16,4 @@ - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index a68e9179c81..06b106b96d3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -16,5 +16,4 @@ - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES index cf0f5c871be..65d841c450c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES @@ -92,31 +92,38 @@ docs/scripts/git_push.ps1 docs/scripts/git_push.sh src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md src/Org.OpenAPITools/Api/AnotherFakeApi.cs src/Org.OpenAPITools/Api/DefaultApi.cs src/Org.OpenAPITools/Api/FakeApi.cs src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +src/Org.OpenAPITools/Api/IApi.cs src/Org.OpenAPITools/Api/PetApi.cs src/Org.OpenAPITools/Api/StoreApi.cs src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs src/Org.OpenAPITools/Client/ApiKeyToken.cs src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/HostConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningToken.cs -src/Org.OpenAPITools/Client/IApi.cs src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs src/Org.OpenAPITools/Client/OAuthToken.cs -src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs src/Org.OpenAPITools/Client/RateLimitProvider`1.cs src/Org.OpenAPITools/Client/TokenBase.cs src/Org.OpenAPITools/Client/TokenContainer`1.cs src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs src/Org.OpenAPITools/Model/Activity.cs src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -197,3 +204,4 @@ src/Org.OpenAPITools/Model/User.cs src/Org.OpenAPITools/Model/Whale.cs src/Org.OpenAPITools/Model/Zebra.cs src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/README.md index de89d86a369..f9c1c7f7462 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/README.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/README.md @@ -1,259 +1 @@ # 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=Org.OpenAPITools', - '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 Org.OpenAPITools.Api; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Model; - -namespace YourProject -{ - public class Program - { - public static async Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); - var api = host.Services.GetRequiredService(); - ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); - } - - 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. - - -## 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 -- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later -- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.1 or later -- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.7.0 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: - - -### 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 - - -### bearer_test - - -- **Type**: Bearer Authentication - - -### http_basic_test - - -- **Type**: HTTP basic authentication - - -### http_signature_test - - - - -### 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 - -## Build -- SDK version: 1.0.0 -- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen - -## 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: Org.OpenAPITools -- 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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md index a179355d603..77826f0673b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md @@ -631,7 +631,7 @@ No authorization required # **TestBodyWithQueryParams** -> void TestBodyWithQueryParams (string query, User user) +> void TestBodyWithQueryParams (User user, string query) @@ -652,12 +652,12 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new FakeApi(config); - var query = "query_example"; // string | var user = new User(); // User | + var query = "query_example"; // string | try { - apiInstance.TestBodyWithQueryParams(query, user); + apiInstance.TestBodyWithQueryParams(user, query); } catch (ApiException e) { @@ -676,7 +676,7 @@ This returns an ApiResponse object which contains the response data, status code ```csharp try { - apiInstance.TestBodyWithQueryParamsWithHttpInfo(query, user); + apiInstance.TestBodyWithQueryParamsWithHttpInfo(user, query); } catch (ApiException e) { @@ -690,8 +690,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **query** | **string** | | | | **user** | [**User**](User.md) | | | +| **query** | **string** | | | ### Return type @@ -807,7 +807,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null) +> void TestEndpointParameters (byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -834,17 +834,17 @@ namespace Example config.Password = "YOUR_PASSWORD"; var apiInstance = new FakeApi(config); + var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | None var number = 8.14D; // decimal | None var _double = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | 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 _float = 3.4F; // float? | None (optional) var integer = 56; // int? | None (optional) var int32 = 56; // int? | None (optional) var int64 = 789L; // long? | None (optional) - var _float = 3.4F; // float? | None (optional) var _string = "_string_example"; // string? | None (optional) - var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream? | None (optional) - var date = DateTime.Parse("2013-10-20"); // DateTime? | 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") @@ -852,7 +852,7 @@ namespace Example try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -872,7 +872,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParametersWithHttpInfo(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -886,17 +886,17 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| +| **_byte** | **byte[]** | None | | | **number** | **decimal** | None | | | **_double** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **_byte** | **byte[]** | None | | +| **date** | **DateTime?** | None | [optional] | +| **binary** | **System.IO.Stream?****System.IO.Stream?** | None | [optional] | +| **_float** | **float?** | None | [optional] | | **integer** | **int?** | None | [optional] | | **int32** | **int?** | None | [optional] | | **int64** | **long?** | None | [optional] | -| **_float** | **float?** | None | [optional] | | **_string** | **string?** | None | [optional] | -| **binary** | **System.IO.Stream?****System.IO.Stream?** | None | [optional] | -| **date** | **DateTime?** | None | [optional] | | **password** | **string?** | None | [optional] | | **callback** | **string?** | None | [optional] | | **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | @@ -925,7 +925,7 @@ void (empty response body) # **TestEnumParameters** -> void TestEnumParameters (List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null) +> 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 @@ -950,17 +950,17 @@ namespace Example 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 enumQueryInteger = 1; // int? | Query parameter enum test (double) (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 enumFormStringArray = new List?(); // List? | Form parameter enum test (string array) (optional) (default to $) var enumFormString = "_abc"; // string? | Form parameter enum test (string) (optional) (default to -efg) try { // To test enum parameters - apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -980,7 +980,7 @@ This returns an ApiResponse object which contains the response data, status code try { // To test enum parameters - apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -996,11 +996,11 @@ catch (ApiException e) |------|------|-------------|-------| | **enumHeaderStringArray** | [**List<string>?**](string.md) | Header parameter enum test (string array) | [optional] | | **enumQueryStringArray** | [**List<string>?**](string.md) | Query parameter enum test (string array) | [optional] | -| **enumQueryInteger** | **int?** | Query parameter enum test (double) | [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] | -| **enumFormStringArray** | [**List<string>?**](string.md) | Form parameter enum test (string array) | [optional] [default to $] | | **enumFormString** | **string?** | Form parameter enum test (string) | [optional] [default to -efg] | ### Return type @@ -1027,7 +1027,7 @@ No authorization required # **TestGroupParameters** -> void TestGroupParameters (int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null) +> void TestGroupParameters (bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null) Fake endpoint to test group parameters (optional) @@ -1053,17 +1053,17 @@ namespace Example config.AccessToken = "YOUR_BEARER_TOKEN"; var apiInstance = new FakeApi(config); - var requiredStringGroup = 56; // int | Required String in group parameters 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 stringGroup = 56; // int? | String in group parameters (optional) 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(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1083,7 +1083,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint to test group parameters (optional) - apiInstance.TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParametersWithHttpInfo(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1097,11 +1097,11 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | +| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredInt64Group** | **long** | Required Integer in group parameters | | -| **stringGroup** | **int?** | String in group parameters | [optional] | | **booleanGroup** | **bool?** | Boolean in group parameters | [optional] | +| **stringGroup** | **int?** | String in group parameters | [optional] | | **int64Group** | **long?** | Integer in group parameters | [optional] | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md index 4187e44c57d..d5e8e8330a0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md @@ -664,7 +664,7 @@ void (empty response body) # **UploadFile** -> ApiResponse UploadFile (long petId, string? additionalMetadata = null, System.IO.Stream? file = null) +> ApiResponse UploadFile (long petId, System.IO.Stream? file = null, string? additionalMetadata = null) uploads an image @@ -689,13 +689,13 @@ namespace Example var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to update - var additionalMetadata = "additionalMetadata_example"; // string? | Additional data to pass to server (optional) 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, additionalMetadata, file); + ApiResponse result = apiInstance.UploadFile(petId, file, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -716,7 +716,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image - ApiResponse response = apiInstance.UploadFileWithHttpInfo(petId, additionalMetadata, file); + 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); @@ -734,8 +734,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| | **petId** | **long** | ID of pet to update | | -| **additionalMetadata** | **string?** | Additional data to pass to server | [optional] | | **file** | **System.IO.Stream?****System.IO.Stream?** | file to upload | [optional] | +| **additionalMetadata** | **string?** | Additional data to pass to server | [optional] | ### Return type @@ -760,7 +760,7 @@ catch (ApiException e) # **UploadFileWithRequiredFile** -> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string? additionalMetadata = null) +> ApiResponse UploadFileWithRequiredFile (System.IO.Stream requiredFile, long petId, string? additionalMetadata = null) uploads an image (required) @@ -784,14 +784,14 @@ namespace Example config.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(config); - var petId = 789L; // long | ID of pet to update 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(petId, requiredFile, additionalMetadata); + ApiResponse result = apiInstance.UploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -812,7 +812,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image (required) - ApiResponse response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + 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); @@ -829,8 +829,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **petId** | **long** | ID of pet to update | | | **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 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md index fd1c1a7d62b..a862c8c112a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md @@ -623,7 +623,7 @@ No authorization required # **UpdateUser** -> void UpdateUser (string username, User user) +> void UpdateUser (User user, string username) Updated user @@ -646,13 +646,13 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new UserApi(config); - var username = "username_example"; // string | name that need to be deleted var user = new User(); // User | Updated user object + var username = "username_example"; // string | name that need to be deleted try { // Updated user - apiInstance.UpdateUser(username, user); + apiInstance.UpdateUser(user, username); } catch (ApiException e) { @@ -672,7 +672,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Updated user - apiInstance.UpdateUserWithHttpInfo(username, user); + apiInstance.UpdateUserWithHttpInfo(user, username); } catch (ApiException e) { @@ -686,8 +686,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **username** | **string** | name that need to be deleted | | | **user** | [**User**](User.md) | Updated user object | | +| **username** | **string** | name that need to be deleted | | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md index 1f919450009..f79869f95a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md @@ -4,14 +4,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapProperty** | **Dictionary<string, string>** | | [optional] +**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] -**Anytype1** | **Object** | | [optional] +**MapProperty** | **Dictionary<string, string>** | | [optional] **MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] -**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ApiResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ApiResponse.md index bc808ceeae3..d89ed1a25dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ApiResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ApiResponse.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | **int** | | [optional] -**Type** | **string** | | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ArrayTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ArrayTest.md index 32365e6d4d0..ed572120cd6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ArrayTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ArrayTest.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayOfString** | **List<string>** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Capitalization.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Capitalization.md index fde98a967ef..9e225c17232 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Capitalization.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Capitalization.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SmallCamel** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [optional] **CapitalCamel** | **string** | | [optional] -**SmallSnake** | **string** | | [optional] **CapitalSnake** | **string** | | [optional] **SCAETHFlowPoints** | **string** | | [optional] -**ATT_NAME** | **string** | Name of the pet | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Category.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Category.md index c2cf3f8e919..6eb0a2e13ea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Category.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Category.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Name** | **string** | | [default to "default-name"] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ClassModel.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ClassModel.md index bb35816c914..a098828a04f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ClassModel.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ClassModel.md @@ -5,7 +5,7 @@ Model for testing model with \"_class\" property Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Class** | **string** | | [optional] +**ClassProperty** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md index 18117e6c938..fcee9662afb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md @@ -6,8 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] -**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **Shapes** | [**List<Shape>**](Shape.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md index 2a27962cc52..7467f67978c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**JustSymbol** | **string** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md index 71602270bab..53bbfe31e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**EnumStringRequired** | **string** | | -**EnumString** | **string** | | [optional] **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] -**OuterEnumInteger** | **OuterEnumInteger** | | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FooGetDefaultResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FooGetDefaultResponse.md index 47e50daca3e..78c99facf59 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FooGetDefaultResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FooGetDefaultResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] +**StringProperty** | [**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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md index 0b92c2fb10a..4e34a6d18b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md @@ -4,22 +4,22 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Number** | **decimal** | | -**Byte** | **byte[]** | | +**Binary** | **System.IO.Stream** | | [optional] +**ByteProperty** | **byte[]** | | **Date** | **DateTime** | | -**Password** | **string** | | -**Integer** | **int** | | [optional] +**DateTime** | **DateTime** | | [optional] +**DecimalProperty** | **decimal** | | [optional] +**DoubleProperty** | **double** | | [optional] +**FloatProperty** | **float** | | [optional] **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] -**Float** | **float** | | [optional] -**Double** | **double** | | [optional] -**Decimal** | **decimal** | | [optional] -**String** | **string** | | [optional] -**Binary** | **System.IO.Stream** | | [optional] -**DateTime** | **DateTime** | | [optional] -**Uuid** | **Guid** | | [optional] +**Integer** | **int** | | [optional] +**Number** | **decimal** | | +**Password** | **string** | | **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] +**StringProperty** | **string** | | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md index aaee09f7870..5dd27228bb0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md index 031d2b96065..0bac85a8e83 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **Guid** | | [optional] **DateTime** | **DateTime** | | [optional] **Map** | [**Dictionary<string, Animal>**](Animal.md) | | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Model200Response.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Model200Response.md index 8bc8049f46f..93139e1d1aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Model200Response.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Model200Response.md @@ -5,8 +5,8 @@ Model for testing model name starting with number Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**ClassProperty** | **string** | | [optional] **Name** | **int** | | [optional] -**Class** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ModelClient.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ModelClient.md index 9e0e83645f3..51cf0636e72 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ModelClient.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ModelClient.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_Client** | **string** | | [optional] +**_ClientProperty** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Name.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Name.md index 2ee782c0c54..11f49b9fd40 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Name.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Name.md @@ -6,8 +6,8 @@ Model for testing model name same as property name Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **NameProperty** | **int** | | -**SnakeCase** | **int** | | [optional] [readonly] **Property** | **string** | | [optional] +**SnakeCase** | **int** | | [optional] [readonly] **_123Number** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md index d4a19d1856b..ac86336ea70 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**IntegerProp** | **int?** | | [optional] -**NumberProp** | **decimal?** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool?** | | [optional] -**StringProp** | **string** | | [optional] **DateProp** | **DateTime?** | | [optional] **DatetimeProp** | **DateTime?** | | [optional] -**ArrayNullableProp** | **List<Object>** | | [optional] -**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**IntegerProp** | **int?** | | [optional] +**NumberProp** | **decimal?** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] -**ObjectItemsNullable** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ObjectWithDeprecatedFields.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ObjectWithDeprecatedFields.md index b737f7d757a..9f44c24d19a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ObjectWithDeprecatedFields.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/ObjectWithDeprecatedFields.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **string** | | [optional] -**Id** | **decimal** | | [optional] -**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/OuterComposite.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/OuterComposite.md index abf676810fb..8985c59d094 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/OuterComposite.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/OuterComposite.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**MyBoolean** | **bool** | | [optional] **MyNumber** | **decimal** | | [optional] **MyString** | **string** | | [optional] -**MyBoolean** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md index 7de10304abf..b13bb576b45 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | -**Id** | **long** | | [optional] -**Category** | [**Category**](Category.md) | | [optional] -**Tags** | [**List<Tag>**](Tag.md) | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/SpecialModelName.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/SpecialModelName.md index 662fa6f4a38..b48f3490005 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/SpecialModelName.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/SpecialModelName.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SpecialPropertyName** | **long** | | [optional] **SpecialModelNameProperty** | **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-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md index a0f0d223899..455f031674d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Username** | **string** | | [optional] -**FirstName** | **string** | | [optional] -**LastName** | **string** | | [optional] **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] -**ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs index fea7e39428f..30f54c0aab5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class AnotherFakeApiTests : ApiTestsBase { - private readonly IAnotherFakeApi _instance; + private readonly IApi.IAnotherFakeApi _instance; public AnotherFakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index 88d6fc1f488..75e37de2412 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Extensions.Hosting; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; /* ********************************************************************************* @@ -49,7 +50,7 @@ namespace Org.OpenAPITools.Test.Api } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureApi((context, options) => + .ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration[""], timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 16f60704f2a..d79076dcd63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class DefaultApiTests : ApiTestsBase { - private readonly IDefaultApi _instance; + private readonly IApi.IDefaultApi _instance; public DefaultApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 4eee3d2b6eb..256df5697c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -13,7 +13,8 @@ using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Security.Cryptography; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; using Xunit; namespace Org.OpenAPITools.Test.Api @@ -24,7 +25,7 @@ namespace Org.OpenAPITools.Test.Api public class DependencyInjectionTest { private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -45,7 +46,7 @@ namespace Org.OpenAPITools.Test.Api .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -121,25 +122,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -149,25 +150,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -177,25 +178,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithAClientTest() { - var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -205,25 +206,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index b20faebe9c4..84ff71fb14d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeApiTests : ApiTestsBase { - private readonly IFakeApi _instance; + private readonly IApi.IFakeApi _instance; public FakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -131,9 +131,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestBodyWithQueryParamsAsyncTest() { - string query = default; User user = default; - await _instance.TestBodyWithQueryParamsAsync(query, user); + string query = default; + await _instance.TestBodyWithQueryParamsAsync(user, query); } /// @@ -153,21 +153,21 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestEndpointParametersAsyncTest() { + byte[] _byte = default; decimal number = default; double _double = default; string patternWithoutDelimiter = default; - byte[] _byte = default; + DateTime? date = default; + System.IO.Stream? binary = default; + float? _float = default; int? integer = default; int? int32 = default; long? int64 = default; - float? _float = default; string? _string = default; - System.IO.Stream? binary = default; - DateTime? date = default; string? password = default; string? callback = default; DateTime? dateTime = default; - await _instance.TestEndpointParametersAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + await _instance.TestEndpointParametersAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } /// @@ -178,13 +178,13 @@ namespace Org.OpenAPITools.Test.Api { List? enumHeaderStringArray = default; List? enumQueryStringArray = default; - int? enumQueryInteger = default; double? enumQueryDouble = default; + int? enumQueryInteger = default; + List? enumFormStringArray = default; string? enumHeaderString = default; string? enumQueryString = default; - List? enumFormStringArray = default; string? enumFormString = default; - await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } /// @@ -193,13 +193,13 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestGroupParametersAsyncTest() { - int requiredStringGroup = default; bool requiredBooleanGroup = default; + int requiredStringGroup = default; long requiredInt64Group = default; - int? stringGroup = default; bool? booleanGroup = default; + int? stringGroup = default; long? int64Group = default; - await _instance.TestGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + await _instance.TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs index 0e8d44fe985..5a34bf585f0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeClassnameTags123ApiTests : ApiTestsBase { - private readonly IFakeClassnameTags123Api _instance; + private readonly IApi.IFakeClassnameTags123Api _instance; public FakeClassnameTags123ApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index 30734616d1f..d539cb5396d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class PetApiTests : ApiTestsBase { - private readonly IPetApi _instance; + private readonly IApi.IPetApi _instance; public PetApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -134,9 +134,9 @@ namespace Org.OpenAPITools.Test.Api public async Task UploadFileAsyncTest() { long petId = default; - string? additionalMetadata = default; System.IO.Stream? file = default; - var response = await _instance.UploadFileAsync(petId, additionalMetadata, file); + string? additionalMetadata = default; + var response = await _instance.UploadFileAsync(petId, file, additionalMetadata); Assert.IsType(response); } @@ -146,10 +146,10 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UploadFileWithRequiredFileAsyncTest() { - long petId = default; System.IO.Stream requiredFile = default; + long petId = default; string? additionalMetadata = default; - var response = await _instance.UploadFileWithRequiredFileAsync(petId, requiredFile, additionalMetadata); + var response = await _instance.UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata); Assert.IsType(response); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index 98748893e32..679d6488380 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class StoreApiTests : ApiTestsBase { - private readonly IStoreApi _instance; + private readonly IApi.IStoreApi _instance; public StoreApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index 0df256733af..b8006066faf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class UserApiTests : ApiTestsBase { - private readonly IUserApi _instance; + private readonly IApi.IUserApi _instance; public UserApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -129,9 +129,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UpdateUserAsyncTest() { - string username = default; User user = default; - await _instance.UpdateUserAsync(username, user); + string username = default; + await _instance.UpdateUserAsync(user, username); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs index f211a64884a..174a7e333af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityTests.cs index afe9e846ee9..c7479a3c343 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ActivityTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index 9ab029ed097..95bd1593503 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'MapProperty' + /// Test the property 'EmptyMap' /// [Fact] - public void MapPropertyTest() + public void EmptyMapTest() { - // TODO unit test for the property 'MapProperty' + // TODO unit test for the property 'EmptyMap' } /// /// Test the property 'MapOfMapProperty' @@ -73,12 +72,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapOfMapProperty' } /// - /// Test the property 'Anytype1' + /// Test the property 'MapProperty' /// [Fact] - public void Anytype1Test() + public void MapPropertyTest() { - // TODO unit test for the property 'Anytype1' + // TODO unit test for the property 'MapProperty' } /// /// Test the property 'MapWithUndeclaredPropertiesAnytype1' @@ -105,14 +104,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' } /// - /// Test the property 'EmptyMap' - /// - [Fact] - public void EmptyMapTest() - { - // TODO unit test for the property 'EmptyMap' - } - /// /// Test the property 'MapWithUndeclaredPropertiesString' /// [Fact] @@ -120,6 +111,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index ced34a4faad..8c38ac47af7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 2a2e098e608..a2a9a2d49de 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Code' } /// - /// Test the property 'Type' - /// - [Fact] - public void TypeTest() - { - // TODO unit test for the property 'Type' - } - /// /// Test the property 'Message' /// [Fact] @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs index f945f659368..0610780d65d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleTests.cs index 468d60184ad..e0bd59e7732 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs index 0b259d7d391..8f046a0bf6b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs index 27f312ad25f..53b2fe30fdb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs index a433e8c87cf..df87ba3aaaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'ArrayOfString' - /// - [Fact] - public void ArrayOfStringTest() - { - // TODO unit test for the property 'ArrayOfString' - } /// /// Test the property 'ArrayArrayOfInteger' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs index 8a6eeb82eee..6f31ba2029b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaTests.cs index 8d8cc376b03..6cb6c62ffd0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs index 3cdccaa7595..9798a17577b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs index 185c83666fc..b84c7c85a7d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'SmallCamel' + /// Test the property 'ATT_NAME' /// [Fact] - public void SmallCamelTest() + public void ATT_NAMETest() { - // TODO unit test for the property 'SmallCamel' + // TODO unit test for the property 'ATT_NAME' } /// /// Test the property 'CapitalCamel' @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'CapitalCamel' } /// - /// Test the property 'SmallSnake' - /// - [Fact] - public void SmallSnakeTest() - { - // TODO unit test for the property 'SmallSnake' - } - /// /// Test the property 'CapitalSnake' /// [Fact] @@ -97,12 +88,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'SCAETHFlowPoints' } /// - /// Test the property 'ATT_NAME' + /// Test the property 'SmallCamel' /// [Fact] - public void ATT_NAMETest() + public void SmallCamelTest() { - // TODO unit test for the property 'ATT_NAME' + // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs index fb51c28489c..3498bb0c152 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatTests.cs index 9c3c48ffefe..402a476d079 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index 621877aa973..822f8241fa0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } /// /// Test the property 'Id' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs index 49a53932490..d4de4c47417 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs index 0fe3ebfa06e..f1b0aa1005c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs index d29472e83aa..2e6c120d8fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Class' + /// Test the property 'ClassProperty' /// [Fact] - public void ClassTest() + public void ClassPropertyTest() { - // TODO unit test for the property 'Class' + // TODO unit test for the property 'ClassProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs index 6c50fe7aab5..3f2f96e73a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs index 572d9bffa79..087d38674bb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs index 1da5f4011c9..85ecbfdda55 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs index b22a4442096..1e86d761507 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogTests.cs index bf906f01bc6..ef2eabfca31 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0709ad9eeb3..c38867cb5ae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ShapeOrNull' } /// - /// Test the property 'NullableShape' - /// - [Fact] - public void NullableShapeTest() - { - // TODO unit test for the property 'NullableShape' - } - /// /// Test the property 'Shapes' /// [Fact] @@ -88,6 +79,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Shapes' } + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs index 5779ca29477..ee3d000f32f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'JustSymbol' - /// - [Fact] - public void JustSymbolTest() - { - // TODO unit test for the property 'JustSymbol' - } /// /// Test the property 'ArrayEnum' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs index a17738c5cbc..e2fc2d02282 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index a22c39ca845..60e3aca92bd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'EnumStringRequired' - /// - [Fact] - public void EnumStringRequiredTest() - { - // TODO unit test for the property 'EnumStringRequired' - } - /// - /// Test the property 'EnumString' - /// - [Fact] - public void EnumStringTest() - { - // TODO unit test for the property 'EnumString' - } /// /// Test the property 'EnumInteger' /// @@ -97,20 +80,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumNumber' } /// - /// Test the property 'OuterEnum' + /// Test the property 'EnumString' /// [Fact] - public void OuterEnumTest() + public void EnumStringTest() { - // TODO unit test for the property 'OuterEnum' + // TODO unit test for the property 'EnumString' } /// - /// Test the property 'OuterEnumInteger' + /// Test the property 'EnumStringRequired' /// [Fact] - public void OuterEnumIntegerTest() + public void EnumStringRequiredTest() { - // TODO unit test for the property 'OuterEnumInteger' + // TODO unit test for the property 'EnumStringRequired' } /// /// Test the property 'OuterEnumDefaultValue' @@ -121,6 +104,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -128,6 +119,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs index 9ca755c4b07..9ab78a59779 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs index 9f45b4fe89d..9836a779bf0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileTests.cs index 761bb72a844..4f0e7079bc8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs index 0154d528418..b7313941a69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'String' + /// Test the property 'StringProperty' /// [Fact] - public void StringTest() + public void StringPropertyTest() { - // TODO unit test for the property 'String' + // TODO unit test for the property 'StringProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooTests.cs index 0b6ed52edbd..c0bdf85f9b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index 707847bbcd1..d3a978bdc4c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,20 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Number' + /// Test the property 'Binary' /// [Fact] - public void NumberTest() + public void BinaryTest() { - // TODO unit test for the property 'Number' + // TODO unit test for the property 'Binary' } /// - /// Test the property 'Byte' + /// Test the property 'ByteProperty' /// [Fact] - public void ByteTest() + public void BytePropertyTest() { - // TODO unit test for the property 'Byte' + // TODO unit test for the property 'ByteProperty' } /// /// Test the property 'Date' @@ -81,20 +80,36 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Date' } /// - /// Test the property 'Password' + /// Test the property 'DateTime' /// [Fact] - public void PasswordTest() + public void DateTimeTest() { - // TODO unit test for the property 'Password' + // TODO unit test for the property 'DateTime' } /// - /// Test the property 'Integer' + /// Test the property 'DecimalProperty' /// [Fact] - public void IntegerTest() + public void DecimalPropertyTest() { - // TODO unit test for the property 'Integer' + // TODO unit test for the property 'DecimalProperty' + } + /// + /// Test the property 'DoubleProperty' + /// + [Fact] + public void DoublePropertyTest() + { + // TODO unit test for the property 'DoubleProperty' + } + /// + /// Test the property 'FloatProperty' + /// + [Fact] + public void FloatPropertyTest() + { + // TODO unit test for the property 'FloatProperty' } /// /// Test the property 'Int32' @@ -113,60 +128,28 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Int64' } /// - /// Test the property 'Float' + /// Test the property 'Integer' /// [Fact] - public void FloatTest() + public void IntegerTest() { - // TODO unit test for the property 'Float' + // TODO unit test for the property 'Integer' } /// - /// Test the property 'Double' + /// Test the property 'Number' /// [Fact] - public void DoubleTest() + public void NumberTest() { - // TODO unit test for the property 'Double' + // TODO unit test for the property 'Number' } /// - /// Test the property 'Decimal' + /// Test the property 'Password' /// [Fact] - public void DecimalTest() + public void PasswordTest() { - // TODO unit test for the property 'Decimal' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' + // TODO unit test for the property 'Password' } /// /// Test the property 'PatternWithDigits' @@ -184,6 +167,22 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'PatternWithDigitsAndDelimiter' } + /// + /// Test the property 'StringProperty' + /// + [Fact] + public void StringPropertyTest() + { + // TODO unit test for the property 'StringProperty' + } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs index 3a0b55b93e3..3ef884e59c6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitTests.cs index ddc424d56ea..9ab6b7f2781 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs index cbd35f9173c..036c5641cf4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index faa4930944b..182cf7350b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs index 651a9f0ce30..d9a07efcf9a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs index 857190a3334..d29edf5dd10 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs index 8e0dae93420..2fed6f0b4cc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ListTests.cs index 2ed828d0520..398a4644921 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ListTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MammalTests.cs index 6477ab950fa..0889d80a708 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MammalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MapTestTests.cs index 20036e1c905..0dc95aa6b23 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MapTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// 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' - } /// /// Test the property 'DirectMap' /// @@ -88,6 +71,22 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index f56cd715f45..d94f882e0a2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' - } /// /// Test the property 'DateTime' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Map' } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs index e25478618f2..31f2a754314 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'ClassProperty' + /// + [Fact] + public void ClassPropertyTest() + { + // TODO unit test for the property 'ClassProperty' + } /// /// Test the property 'Name' /// @@ -64,14 +71,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Name' } - /// - /// Test the property 'Class' - /// - [Fact] - public void ClassTest() - { - // TODO unit test for the property 'Class' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 24a9e263158..40b3700ce95 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '_Client' + /// Test the property '_ClientProperty' /// [Fact] - public void _ClientTest() + public void _ClientPropertyTest() { - // TODO unit test for the property '_Client' + // TODO unit test for the property '_ClientProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NameTests.cs index 61f8ad11379..523b3e050aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'NameProperty' } /// - /// Test the property 'SnakeCase' - /// - [Fact] - public void SnakeCaseTest() - { - // TODO unit test for the property 'SnakeCase' - } - /// /// Test the property 'Property' /// [Fact] @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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 '_123Number' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 8f00505612a..adf7c14f131 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,36 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'IntegerProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void IntegerPropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'IntegerProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// - /// Test the property 'NumberProp' + /// Test the property 'ObjectItemsNullable' /// [Fact] - public void NumberPropTest() + public void ObjectItemsNullableTest() { - // TODO unit test for the property 'NumberProp' + // 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' @@ -81,14 +96,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'BooleanProp' } /// - /// Test the property 'StringProp' - /// - [Fact] - public void StringPropTest() - { - // TODO unit test for the property 'StringProp' - } - /// /// Test the property 'DateProp' /// [Fact] @@ -105,36 +112,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DatetimeProp' } /// - /// Test the property 'ArrayNullableProp' + /// Test the property 'IntegerProp' /// [Fact] - public void ArrayNullablePropTest() + public void IntegerPropTest() { - // TODO unit test for the property 'ArrayNullableProp' + // TODO unit test for the property 'IntegerProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'NumberProp' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void NumberPropTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' - } - /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - /// - /// Test the property 'ObjectNullableProp' - /// - [Fact] - public void ObjectNullablePropTest() - { - // TODO unit test for the property 'ObjectNullableProp' + // TODO unit test for the property 'NumberProp' } /// /// Test the property 'ObjectAndItemsNullableProp' @@ -145,12 +136,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ObjectAndItemsNullableProp' } /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ObjectNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ObjectNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs index 8202ef63914..734d03e5e7a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs index 3a06cb020b2..5db923c1d3f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs index 82f93fab48c..9e9b651f818 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Uuid' + /// Test the property 'Bars' /// [Fact] - public void UuidTest() + public void BarsTest() { - // TODO unit test for the property 'Uuid' - } - /// - /// Test the property 'Id' - /// - [Fact] - public void IdTest() - { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'Bars' } /// /// Test the property 'DeprecatedRef' @@ -81,12 +72,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DeprecatedRef' } /// - /// Test the property 'Bars' + /// Test the property 'Id' /// [Fact] - public void BarsTest() + public void IdTest() { - // TODO unit test for the property 'Bars' + // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs index cf5c561c547..10682e72f21 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs index 2efda0db59c..8c176d9f94c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } /// /// Test the property 'MyNumber' /// @@ -72,14 +79,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'MyString' } - /// - /// Test the property 'MyBoolean' - /// - [Fact] - public void MyBooleanTest() - { - // TODO unit test for the property 'MyBoolean' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs index 986fff774c4..9f6d8b52b6c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs index 015d5dab945..e51365edb27 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs index 385e899110a..36e6a060f97 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs index f47304767b9..b38c693d1a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs index 1e17568ed33..34cae43eac1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs index 28ea4d8478d..66cfbf7bdb5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,22 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// 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' /// @@ -73,20 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Id' + /// Test the property 'Status' /// [Fact] - public void IdTest() + public void StatusTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Category' - /// - [Fact] - public void CategoryTest() - { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Status' } /// /// Test the property 'Tags' @@ -96,14 +103,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Tags' } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PigTests.cs index a66befe8f58..0e85eabf160 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs index eff3c6ddc9b..98aad34f4b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs index 6eef9f4c816..42243bd29c0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs index 3d62673d093..e15b2c5c749 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs index dc3d0fad54c..7e99972f26e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReturnTests.cs index 65fa199fe35..9969564490d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReturnTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs index 018dffb5964..cad95d2963c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs index 7bd0bc86f96..3129f3775c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs index ef564357648..a33da20eda6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeTests.cs index 783a9657ed4..b2d995af504 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs index 3bcd65e792d..0221971c076 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 91682a7afd6..1a5bb10af80 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'SpecialPropertyName' - /// - [Fact] - public void SpecialPropertyNameTest() - { - // TODO unit test for the property 'SpecialPropertyName' - } /// /// Test the property 'SpecialModelNameProperty' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialModelNameProperty' } + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TagTests.cs index 6d56232d0a7..92a5f823659 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs index fba65470bee..924d6b42d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleTests.cs index bdaab0b4796..9701da6a541 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs index a7b095e4c28..a464c80c84c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Id' + /// Test the property 'Email' /// [Fact] - public void IdTest() + public void EmailTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Username' - /// - [Fact] - public void UsernameTest() - { - // TODO unit test for the property 'Username' + // TODO unit test for the property 'Email' } /// /// Test the property 'FirstName' @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -89,12 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'LastName' } /// - /// Test the property 'Email' + /// Test the property 'ObjectWithNoDeclaredProps' /// [Fact] - public void EmailTest() + public void ObjectWithNoDeclaredPropsTest() { - // TODO unit test for the property 'Email' + // TODO unit test for the property 'ObjectWithNoDeclaredProps' } /// /// Test the property 'Password' @@ -121,20 +120,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'UserStatus' } /// - /// Test the property 'ObjectWithNoDeclaredProps' + /// Test the property 'Username' /// [Fact] - public void ObjectWithNoDeclaredPropsTest() + public void UsernameTest() { - // TODO unit test for the property 'ObjectWithNoDeclaredProps' - } - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + // TODO unit test for the property 'Username' } /// /// Test the property 'AnyTypeProp' @@ -152,6 +143,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/WhaleTests.cs index 9b82c29c8fd..91a7b21f213 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/WhaleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ZebraTests.cs index 39e0561fe0f..08b1c6056c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ZebraTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 0a1564bcf56..96b9fd0c60e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,13 +9,12 @@ - + - + - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 87be0ad41e0..a74ad308ba2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IAnotherFakeApi : IApi { @@ -50,7 +51,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); /// /// To test special tags @@ -62,22 +63,18 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient?> Task Call123TestSpecialTagsOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} - } - +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class AnotherFakeApi : IAnotherFakeApi + public partial class AnotherFakeApi : IApi.IAnotherFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -134,6 +131,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -141,7 +147,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// <> - public async Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) + public async Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await Call123TestSpecialTagsWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); @@ -174,6 +180,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnCall123TestSpecialTags(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCall123TestSpecialTags(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCall123TestSpecialTags(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -183,18 +229,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnCall123TestSpecialTags(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -204,6 +246,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -213,7 +257,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -223,31 +267,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCall123TestSpecialTags(apiResponse, modelClient); + } return apiResponse; } @@ -255,8 +292,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCall123TestSpecialTags(e, "/another-fake/dummy", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/DefaultApi.cs index 74a3ab0165d..c7947592799 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IDefaultApi : IApi { @@ -48,7 +49,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<FooGetDefaultResponse> - Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); + Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -59,22 +60,18 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<FooGetDefaultResponse?> Task FooGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); + } +} - } - +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class DefaultApi : IDefaultApi + public partial class DefaultApi : IApi.IDefaultApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -131,13 +128,22 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// /// /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// <> - public async Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null) + public async Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FooGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); @@ -169,6 +175,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFooGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFooGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFooGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// @@ -177,16 +211,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FooGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFooGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/foo"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -197,31 +236,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFooGet(apiResponse); + } return apiResponse; } @@ -229,8 +261,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFooGet(e, "/foo", uriBuilder.Path); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs index 56d7a03ec38..8732ee2357c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeApi : IApi { @@ -48,7 +49,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<HealthCheckResult> - Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null); + Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null); /// /// Health check endpoint @@ -60,7 +61,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<HealthCheckResult?> Task FakeHealthGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -83,7 +83,7 @@ namespace Org.OpenAPITools.Api /// Input boolean as post body (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<bool> - Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null); + Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -96,7 +96,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<bool?> Task FakeOuterBooleanSerializeOrDefaultAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -119,7 +118,7 @@ namespace Org.OpenAPITools.Api /// Input composite as post body (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<OuterComposite> - Task FakeOuterCompositeSerializeAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null); + Task FakeOuterCompositeSerializeAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -132,7 +131,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<OuterComposite?> Task FakeOuterCompositeSerializeOrDefaultAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -155,7 +153,7 @@ namespace Org.OpenAPITools.Api /// Input number as post body (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<decimal> - Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null); + Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -168,7 +166,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<decimal?> Task FakeOuterNumberSerializeOrDefaultAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -191,7 +188,7 @@ namespace Org.OpenAPITools.Api /// Input string as post body (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> - Task FakeOuterStringSerializeAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null); + Task FakeOuterStringSerializeAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -204,7 +201,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<string?> Task FakeOuterStringSerializeOrDefaultAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// Array of Enums /// @@ -225,7 +221,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<OuterEnum>> - Task?> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null); + Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null); /// /// Array of Enums @@ -237,7 +233,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<List<OuterEnum>?> Task?> GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -260,7 +255,7 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null); + Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -273,7 +268,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task TestBodyWithFileSchemaOrDefaultAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -281,11 +275,11 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// Task<ApiResponse<object?>> - Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); + Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -294,11 +288,11 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); + Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -306,13 +300,12 @@ namespace Org.OpenAPITools.Api /// /// /// - /// /// + /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object?> - Task TestBodyWithQueryParamsOrDefaultAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); + Task TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); - /// /// To test \"client\" model /// @@ -335,7 +328,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); /// /// To test \"client\" model @@ -348,7 +341,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<ModelClient?> Task TestClientModelOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); - /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// @@ -356,23 +348,23 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); + Task> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -381,23 +373,23 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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 of ApiResponse<object> - Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -405,43 +397,23 @@ namespace Org.OpenAPITools.Api /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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 of ApiResponse<object?> - Task TestEndpointParametersOrDefaultAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = 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) - /// Header parameter enum test (string) (optional, default to -efg) - /// Query parameter enum test (string) (optional, default to -efg) - /// Form parameter enum test (string array) (optional, default to $) - /// Form parameter enum test (string) (optional, default to -efg) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object?>> - Task> TestEnumParametersWithHttpInfoAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEndpointParametersOrDefaultAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// To test enum parameters @@ -452,15 +424,34 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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> TestEnumParametersWithHttpInfoAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestEnumParametersAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEnumParametersAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); /// /// To test enum parameters @@ -470,17 +461,16 @@ namespace Org.OpenAPITools.Api /// /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// Task of ApiResponse<object?> - Task TestEnumParametersOrDefaultAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEnumParametersOrDefaultAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// Fake endpoint to test group parameters (optional) /// @@ -488,15 +478,15 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint to test group parameters (optional) @@ -505,15 +495,15 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint to test group parameters (optional) @@ -521,17 +511,16 @@ namespace Org.OpenAPITools.Api /// /// Fake endpoint to test group parameters (optional) /// - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<object?> - Task TestGroupParametersOrDefaultAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// test inline additionalProperties /// @@ -554,7 +543,7 @@ namespace Org.OpenAPITools.Api /// request body /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null); + Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null); /// /// test inline additionalProperties @@ -567,7 +556,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task TestInlineAdditionalPropertiesOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null); - /// /// test json serialization of form data /// @@ -592,7 +580,7 @@ namespace Org.OpenAPITools.Api /// field2 /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null); + Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null); /// /// test json serialization of form data @@ -606,7 +594,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task TestJsonFormDataOrDefaultAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null); - /// /// /// @@ -637,7 +624,7 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); + Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -653,22 +640,18 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object?> Task TestQueryParameterCollectionFormatOrDefaultAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); + } +} - } - +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeApi : IFakeApi + public partial class FakeApi : IApi.IFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -725,13 +708,22 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Health check endpoint /// /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// <> - public async Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null) + public async Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FakeHealthGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); @@ -763,6 +755,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFakeHealthGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFakeHealthGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFakeHealthGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Health check endpoint /// @@ -771,16 +791,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeHealthGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFakeHealthGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/health"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -791,31 +816,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeHealthGet(apiResponse); + } return apiResponse; } @@ -823,7 +841,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeHealthGet(e, "/fake/health", uriBuilder.Path); throw; } } @@ -835,14 +853,14 @@ namespace Org.OpenAPITools.Api /// Input boolean as post body (optional) /// Cancellation Token to cancel the request. /// <> - public async Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FakeOuterBooleanSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); - return result.Content; + return result.Content.Value; } /// @@ -868,6 +886,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual bool? OnFakeOuterBooleanSerialize(bool? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterBooleanSerialize(ApiResponse apiResponse, bool? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterBooleanSerialize(Exception exception, string pathFormat, string path, bool? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer boolean types /// @@ -877,11 +926,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterBooleanSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -891,6 +943,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -900,7 +954,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -910,31 +964,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterBooleanSerialize(apiResponse, body); + } return apiResponse; } @@ -942,7 +989,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterBooleanSerialize(e, "/fake/outer/boolean", uriBuilder.Path, body); throw; } } @@ -954,7 +1001,7 @@ namespace Org.OpenAPITools.Api /// Input composite as post body (optional) /// Cancellation Token to cancel the request. /// <> - public async Task FakeOuterCompositeSerializeAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task FakeOuterCompositeSerializeAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FakeOuterCompositeSerializeWithHttpInfoAsync(outerComposite, cancellationToken).ConfigureAwait(false); @@ -987,6 +1034,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual OuterComposite? OnFakeOuterCompositeSerialize(OuterComposite? outerComposite) + { + return outerComposite; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterCompositeSerialize(ApiResponse apiResponse, OuterComposite? outerComposite) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterCompositeSerialize(Exception exception, string pathFormat, string path, OuterComposite? outerComposite) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of object with outer number type /// @@ -996,11 +1074,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite? outerComposite = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + outerComposite = OnFakeOuterCompositeSerialize(outerComposite); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1010,6 +1091,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(outerComposite, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1019,7 +1102,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -1029,31 +1112,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterCompositeSerialize(apiResponse, outerComposite); + } return apiResponse; } @@ -1061,7 +1137,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterCompositeSerialize(e, "/fake/outer/composite", uriBuilder.Path, outerComposite); throw; } } @@ -1073,14 +1149,14 @@ namespace Org.OpenAPITools.Api /// Input number as post body (optional) /// Cancellation Token to cancel the request. /// <> - public async Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FakeOuterNumberSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); - return result.Content; + return result.Content.Value; } /// @@ -1106,6 +1182,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual decimal? OnFakeOuterNumberSerialize(decimal? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterNumberSerialize(ApiResponse apiResponse, decimal? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterNumberSerialize(Exception exception, string pathFormat, string path, decimal? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer number types /// @@ -1115,11 +1222,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterNumberSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1129,6 +1239,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1138,7 +1250,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -1148,31 +1260,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterNumberSerialize(apiResponse, body); + } return apiResponse; } @@ -1180,7 +1285,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterNumberSerialize(e, "/fake/outer/number", uriBuilder.Path, body); throw; } } @@ -1192,7 +1297,7 @@ namespace Org.OpenAPITools.Api /// Input string as post body (optional) /// Cancellation Token to cancel the request. /// <> - public async Task FakeOuterStringSerializeAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task FakeOuterStringSerializeAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await FakeOuterStringSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); @@ -1225,6 +1330,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string? OnFakeOuterStringSerialize(string? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterStringSerialize(ApiResponse apiResponse, string? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterStringSerialize(Exception exception, string pathFormat, string path, string? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer string types /// @@ -1234,11 +1370,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterStringSerializeWithHttpInfoAsync(string? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterStringSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1248,6 +1387,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1257,7 +1398,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -1267,31 +1408,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterStringSerialize(apiResponse, body); + } return apiResponse; } @@ -1299,7 +1433,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterStringSerialize(e, "/fake/outer/string", uriBuilder.Path, body); throw; } } @@ -1310,7 +1444,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// <> - public async Task?> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null) + public async Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null) { ApiResponse?> result = await GetArrayOfEnumsWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); @@ -1342,6 +1476,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetArrayOfEnums() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetArrayOfEnums(ApiResponse?> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetArrayOfEnums(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Array of Enums /// @@ -1350,16 +1512,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task?>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetArrayOfEnums(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/array-of-enums"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -1370,31 +1537,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse?> apiResponse = new ApiResponse?>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetArrayOfEnums(apiResponse); + } return apiResponse; } @@ -1402,7 +1562,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetArrayOfEnums(e, "/fake/array-of-enums", uriBuilder.Path); throw; } } @@ -1414,7 +1574,7 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestBodyWithFileSchemaWithHttpInfoAsync(fileSchemaTestClass, cancellationToken).ConfigureAwait(false); @@ -1447,6 +1607,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual FileSchemaTestClass OnTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (fileSchemaTestClass == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return fileSchemaTestClass; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestBodyWithFileSchema(ApiResponse apiResponse, FileSchemaTestClass fileSchemaTestClass) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithFileSchema(Exception exception, string pathFormat, string path, FileSchemaTestClass fileSchemaTestClass) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// For this test, the body for this request much reference a schema named `File`. /// @@ -1456,18 +1656,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (fileSchemaTestClass == null) - throw new ArgumentNullException(nameof(fileSchemaTestClass)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + fileSchemaTestClass = OnTestBodyWithFileSchema(fileSchemaTestClass); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1477,6 +1673,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(fileSchemaTestClass, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1486,32 +1684,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithFileSchema(apiResponse, fileSchemaTestClass); + } return apiResponse; } @@ -1519,7 +1710,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithFileSchema(e, "/fake/body-with-file-schema", uriBuilder.Path, fileSchemaTestClass); throw; } } @@ -1528,13 +1719,13 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1546,16 +1737,16 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsOrDefaultAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1566,31 +1757,72 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnTestBodyWithQueryParams(User user, string query) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (query == null) + throw new ArgumentNullException(nameof(query)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, query); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestBodyWithQueryParams(ApiResponse apiResponse, User user, string query) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithQueryParams(Exception exception, string pathFormat, string path, User user, string query) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (query == null) - throw new ArgumentNullException(nameof(query)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestBodyWithQueryParams(user, query); + user = validatedParameters.Item1; + query = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1606,6 +1838,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1615,32 +1849,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithQueryParams(apiResponse, user, query); + } return apiResponse; } @@ -1648,7 +1875,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithQueryParams(e, "/fake/body-with-query-params", uriBuilder.Path, user, query); throw; } } @@ -1660,7 +1887,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// <> - public async Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestClientModelWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); @@ -1693,6 +1920,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClientModel(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClientModel(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClientModel(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test \"client\" model To test \"client\" model /// @@ -1702,18 +1969,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClientModel(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1723,6 +1986,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1732,7 +1997,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1742,31 +2007,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClientModel(apiResponse, modelClient); + } return apiResponse; } @@ -1774,7 +2032,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClientModel(e, "/fake", uriBuilder.Path, modelClient); throw; } } @@ -1783,25 +2041,25 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1813,28 +2071,28 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersOrDefaultAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersOrDefaultAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1845,49 +2103,138 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (byte[], decimal, double, string, DateTime?, System.IO.Stream?, float?, int?, int?, long?, string?, string?, string?, DateTime?) OnTestEndpointParameters(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream? binary, float? _float, int? integer, int? int32, long? int64, string? _string, string? password, string? callback, DateTime? dateTime) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_byte == null) + throw new ArgumentNullException(nameof(_byte)); + + if (number == null) + throw new ArgumentNullException(nameof(number)); + + if (_double == null) + throw new ArgumentNullException(nameof(_double)); + + if (patternWithoutDelimiter == null) + throw new ArgumentNullException(nameof(patternWithoutDelimiter)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEndpointParameters(ApiResponse apiResponse, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream? binary, float? _float, int? integer, int? int32, long? int64, string? _string, string? password, string? callback, DateTime? dateTime) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEndpointParameters(Exception exception, string pathFormat, string path, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream? binary, float? _float, int? integer, int? int32, long? int64, string? _string, string? password, string? callback, DateTime? dateTime) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string? _string = null, System.IO.Stream? binary = null, DateTime? date = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream? binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string? _string = null, string? password = null, string? callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (number == null) - throw new ArgumentNullException(nameof(number)); - - if (_double == null) - throw new ArgumentNullException(nameof(_double)); - - if (patternWithoutDelimiter == null) - throw new ArgumentNullException(nameof(patternWithoutDelimiter)); - - if (_byte == null) - throw new ArgumentNullException(nameof(_byte)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + _byte = validatedParameters.Item1; + number = validatedParameters.Item2; + _double = validatedParameters.Item3; + patternWithoutDelimiter = validatedParameters.Item4; + date = validatedParameters.Item5; + binary = validatedParameters.Item6; + _float = validatedParameters.Item7; + integer = validatedParameters.Item8; + int32 = validatedParameters.Item9; + int64 = validatedParameters.Item10; + _string = validatedParameters.Item11; + password = validatedParameters.Item12; + callback = validatedParameters.Item13; + dateTime = validatedParameters.Item14; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1901,13 +2248,28 @@ namespace Org.OpenAPITools.Api multipartContent.Add(new FormUrlEncodedContent(formParams)); + formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + + + formParams.Add(new KeyValuePair("number", ClientUtils.ParameterToString(number))); + + formParams.Add(new KeyValuePair("double", ClientUtils.ParameterToString(_double))); + + formParams.Add(new KeyValuePair("pattern_without_delimiter", ClientUtils.ParameterToString(patternWithoutDelimiter))); - formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + if (date != null) + formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); + + if (binary != null) + multipartContent.Add(new StreamContent(binary)); + + if (_float != null) + formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); if (integer != null) formParams.Add(new KeyValuePair("integer", ClientUtils.ParameterToString(integer))); @@ -1918,18 +2280,9 @@ namespace Org.OpenAPITools.Api if (int64 != null) formParams.Add(new KeyValuePair("int64", ClientUtils.ParameterToString(int64))); - if (_float != null) - formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); - if (_string != null) formParams.Add(new KeyValuePair("string", ClientUtils.ParameterToString(_string))); - if (binary != null) - multipartContent.Add(new StreamContent(binary)); - - if (date != null) - formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); - if (password != null) formParams.Add(new KeyValuePair("password", ClientUtils.ParameterToString(password))); @@ -1941,6 +2294,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BasicToken basicToken = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1956,32 +2311,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEndpointParameters(apiResponse, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1992,7 +2340,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEndpointParameters(e, "/fake", uriBuilder.Path, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); throw; } } @@ -2003,17 +2351,17 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -2027,20 +2375,20 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersOrDefaultAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersOrDefaultAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -2051,27 +2399,90 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (List?, List?, double?, int?, List?, string?, string?, string?) OnTestEnumParameters(List? enumHeaderStringArray, List? enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List? enumFormStringArray, string? enumHeaderString, string? enumQueryString, string? enumFormString) + { + return (enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEnumParameters(ApiResponse apiResponse, List? enumHeaderStringArray, List? enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List? enumFormStringArray, string? enumHeaderString, string? enumQueryString, string? enumFormString) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEnumParameters(Exception exception, string pathFormat, string path, List? enumHeaderStringArray, List? enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List? enumFormStringArray, string? enumHeaderString, string? enumQueryString, string? enumFormString) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestEnumParametersWithHttpInfoAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List? enumFormStringArray = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEnumParametersWithHttpInfoAsync(List? enumHeaderStringArray = null, List? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + var validatedParameters = OnTestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + enumHeaderStringArray = validatedParameters.Item1; + enumQueryStringArray = validatedParameters.Item2; + enumQueryDouble = validatedParameters.Item3; + enumQueryInteger = validatedParameters.Item4; + enumFormStringArray = validatedParameters.Item5; + enumHeaderString = validatedParameters.Item6; + enumQueryString = validatedParameters.Item7; + enumFormString = validatedParameters.Item8; + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2081,12 +2492,12 @@ namespace Org.OpenAPITools.Api if (enumQueryStringArray != null) parseQueryString["enum_query_string_array"] = Uri.EscapeDataString(enumQueryStringArray.ToString()!); - if (enumQueryInteger != null) - parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()!); - if (enumQueryDouble != null) parseQueryString["enum_query_double"] = Uri.EscapeDataString(enumQueryDouble.ToString()!); + if (enumQueryInteger != null) + parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()!); + if (enumQueryString != null) parseQueryString["enum_query_string"] = Uri.EscapeDataString(enumQueryString.ToString()!); @@ -2104,14 +2515,14 @@ namespace Org.OpenAPITools.Api List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (enumFormStringArray != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (enumFormStringArray != null) formParams.Add(new KeyValuePair("enum_form_string_array", ClientUtils.ParameterToString(enumFormStringArray))); if (enumFormString != null) formParams.Add(new KeyValuePair("enum_form_string", ClientUtils.ParameterToString(enumFormString))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2121,32 +2532,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEnumParameters(apiResponse, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } return apiResponse; } @@ -2154,7 +2558,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEnumParameters(e, "/fake", uriBuilder.Path, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); throw; } } @@ -2163,17 +2567,17 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -2185,20 +2589,20 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersOrDefaultAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -2209,38 +2613,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (bool, int, long, bool?, int?, long?) OnTestGroupParameters(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredBooleanGroup == null) + throw new ArgumentNullException(nameof(requiredBooleanGroup)); + + if (requiredStringGroup == null) + throw new ArgumentNullException(nameof(requiredStringGroup)); + + if (requiredInt64Group == null) + throw new ArgumentNullException(nameof(requiredInt64Group)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestGroupParameters(ApiResponse apiResponse, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestGroupParameters(Exception exception, string pathFormat, string path, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requiredStringGroup == null) - throw new ArgumentNullException(nameof(requiredStringGroup)); - - if (requiredBooleanGroup == null) - throw new ArgumentNullException(nameof(requiredBooleanGroup)); - - if (requiredInt64Group == null) - throw new ArgumentNullException(nameof(requiredInt64Group)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + requiredBooleanGroup = validatedParameters.Item1; + requiredStringGroup = validatedParameters.Item2; + requiredInt64Group = validatedParameters.Item3; + booleanGroup = validatedParameters.Item4; + stringGroup = validatedParameters.Item5; + int64Group = validatedParameters.Item6; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2266,6 +2727,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BearerToken bearerToken = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -2276,28 +2739,21 @@ namespace Org.OpenAPITools.Api request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestGroupParameters(apiResponse, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -2308,7 +2764,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestGroupParameters(e, "/fake", uriBuilder.Path, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); throw; } } @@ -2320,7 +2776,7 @@ namespace Org.OpenAPITools.Api /// request body /// Cancellation Token to cancel the request. /// <> - public async Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestInlineAdditionalPropertiesWithHttpInfoAsync(requestBody, cancellationToken).ConfigureAwait(false); @@ -2353,6 +2809,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Dictionary OnTestInlineAdditionalProperties(Dictionary requestBody) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return requestBody; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestInlineAdditionalProperties(ApiResponse apiResponse, Dictionary requestBody) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestInlineAdditionalProperties(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test inline additionalProperties /// @@ -2362,18 +2858,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requestBody == null) - throw new ArgumentNullException(nameof(requestBody)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + requestBody = OnTestInlineAdditionalProperties(requestBody); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2383,6 +2875,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2392,32 +2886,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestInlineAdditionalProperties(apiResponse, requestBody); + } return apiResponse; } @@ -2425,7 +2912,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestInlineAdditionalProperties(e, "/fake/inline-additionalProperties", uriBuilder.Path, requestBody); throw; } } @@ -2438,7 +2925,7 @@ namespace Org.OpenAPITools.Api /// field2 /// Cancellation Token to cancel the request. /// <> - public async Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestJsonFormDataWithHttpInfoAsync(param, param2, cancellationToken).ConfigureAwait(false); @@ -2472,6 +2959,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnTestJsonFormData(string param, string param2) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (param == null) + throw new ArgumentNullException(nameof(param)); + + if (param2 == null) + throw new ArgumentNullException(nameof(param2)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (param, param2); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestJsonFormData(ApiResponse apiResponse, string param, string param2) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestJsonFormData(Exception exception, string pathFormat, string path, string param, string param2) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test json serialization of form data /// @@ -2482,21 +3015,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (param == null) - throw new ArgumentNullException(nameof(param)); - - if (param2 == null) - throw new ArgumentNullException(nameof(param2)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestJsonFormData(param, param2); + param = validatedParameters.Item1; + param2 = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2512,8 +3040,12 @@ namespace Org.OpenAPITools.Api formParams.Add(new KeyValuePair("param", ClientUtils.ParameterToString(param))); + + formParams.Add(new KeyValuePair("param2", ClientUtils.ParameterToString(param2))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2523,32 +3055,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestJsonFormData(apiResponse, param, param2); + } return apiResponse; } @@ -2556,7 +3081,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestJsonFormData(e, "/fake/jsonFormData", uriBuilder.Path, param, param2); throw; } } @@ -2572,7 +3097,7 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// <> - public async Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestQueryParameterCollectionFormatWithHttpInfoAsync(pipe, ioutil, http, url, context, cancellationToken).ConfigureAwait(false); @@ -2609,6 +3134,70 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + protected virtual (List, List, List, List, List) OnTestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + 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)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (pipe, ioutil, http, url, context); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestQueryParameterCollectionFormat(ApiResponse apiResponse, List pipe, List ioutil, List http, List url, List context) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestQueryParameterCollectionFormat(Exception exception, string pathFormat, string path, List pipe, List ioutil, List http, List url, List context) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test the collection format in query parameters /// @@ -2622,30 +3211,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - 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)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + pipe = validatedParameters.Item1; + ioutil = validatedParameters.Item2; + http = validatedParameters.Item3; + url = validatedParameters.Item4; + context = validatedParameters.Item5; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2661,32 +3239,27 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestQueryParameterCollectionFormat(apiResponse, pipe, ioutil, http, url, context); + } return apiResponse; } @@ -2694,8 +3267,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestQueryParameterCollectionFormat(e, "/fake/test-query-parameters", uriBuilder.Path, pipe, ioutil, http, url, context); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 631e6abe154..4bdb85c7203 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeClassnameTags123Api : IApi { @@ -50,7 +51,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); /// /// To test class name in snake case @@ -62,22 +63,18 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient?> Task TestClassnameOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} - } - +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + public partial class FakeClassnameTags123Api : IApi.IFakeClassnameTags123Api { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -134,6 +131,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -141,7 +147,7 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// <> - public async Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await TestClassnameWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); @@ -174,6 +180,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClassname(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClassname(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClassname(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -183,26 +229,22 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClassname(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake_classname_test"; - System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); - request.Content = (modelClient as object) is System.IO.Stream stream + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); request.Content = (modelClient as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); @@ -225,7 +267,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -235,31 +277,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClassname(apiResponse, modelClient); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -270,8 +305,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClassname(e, "/fake_classname_test", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 00000000000..038f19bcfa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs index b86139fcd5f..0e46e92ad02 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IPetApi : IApi { @@ -50,7 +51,7 @@ namespace Org.OpenAPITools.Api /// Pet object that needs to be added to the store /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); /// /// Add a new pet to the store @@ -63,7 +64,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task AddPetOrDefaultAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); - /// /// Deletes a pet /// @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Api /// (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task DeletePetAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null); + Task DeletePetAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Deletes a pet @@ -102,7 +102,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task DeletePetOrDefaultAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// Finds Pets by status /// @@ -125,7 +124,7 @@ namespace Org.OpenAPITools.Api /// Status values that need to be considered for filter /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> - Task?> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null); + Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null); /// /// Finds Pets by status @@ -138,7 +137,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<List<Pet>?> Task?> FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken? cancellationToken = null); - /// /// Finds Pets by tags /// @@ -161,7 +159,7 @@ namespace Org.OpenAPITools.Api /// Tags to filter by /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> - Task?> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null); + Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null); /// /// Finds Pets by tags @@ -174,7 +172,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<List<Pet>?> Task?> FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken? cancellationToken = null); - /// /// Find pet by ID /// @@ -197,7 +194,7 @@ namespace Org.OpenAPITools.Api /// ID of pet to return /// Cancellation Token to cancel the request. /// Task of ApiResponse<Pet> - Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null); + Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null); /// /// Find pet by ID @@ -210,7 +207,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<Pet?> Task GetPetByIdOrDefaultAsync(long petId, System.Threading.CancellationToken? cancellationToken = null); - /// /// Update an existing pet /// @@ -233,7 +229,7 @@ namespace Org.OpenAPITools.Api /// Pet object that needs to be added to the store /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); /// /// Update an existing pet @@ -246,7 +242,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task UpdatePetOrDefaultAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); - /// /// Updates a pet in the store with form data /// @@ -273,7 +268,7 @@ namespace Org.OpenAPITools.Api /// Updated status of the pet (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task UpdatePetWithFormAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null); + Task UpdatePetWithFormAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Updates a pet in the store with form data @@ -288,7 +283,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task UpdatePetWithFormOrDefaultAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null); - /// /// uploads an image /// @@ -297,53 +291,38 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<ApiResponse?>> - Task> UploadFileWithHttpInfoAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server (optional) - /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task of ApiResponse<ApiResponse> - Task UploadFileAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// ID of pet to update - /// Additional data to pass to server (optional) - /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task of ApiResponse<ApiResponse?> - Task UploadFileOrDefaultAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null); - - - /// - /// uploads an image (required) - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// file to upload /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task<ApiResponse<ApiResponse?>> - Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = 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. + /// Task of ApiResponse<ApiResponse> + Task UploadFileAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// 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 of ApiResponse<ApiResponse?> + Task UploadFileOrDefaultAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image (required) @@ -352,12 +331,12 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. - /// Task of ApiResponse<ApiResponse> - Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + /// Task<ApiResponse<ApiResponse?>> + Task> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image (required) @@ -365,28 +344,38 @@ namespace Org.OpenAPITools.Api /// /// /// - /// ID of pet to update + /// 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 of ApiResponse<ApiResponse> + Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// 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 of ApiResponse<ApiResponse?> - Task UploadFileWithRequiredFileOrDefaultAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); - - } + Task UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class PetApi : IPetApi + public partial class PetApi : IApi.IPetApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -443,6 +432,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Add a new pet to the store /// @@ -450,7 +448,7 @@ namespace Org.OpenAPITools.Api /// Pet object that needs to be added to the store /// Cancellation Token to cancel the request. /// <> - public async Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) + public async Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await AddPetWithHttpInfoAsync(pet, cancellationToken).ConfigureAwait(false); @@ -483,6 +481,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnAddPet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterAddPet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorAddPet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Add a new pet to the store /// @@ -492,22 +530,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> AddPetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnAddPet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress!.Host; - uriBuilder.Port = HttpClient.BaseAddress!.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -515,6 +549,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -539,32 +575,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterAddPet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -578,7 +607,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorAddPet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -591,7 +620,7 @@ namespace Org.OpenAPITools.Api /// (optional) /// Cancellation Token to cancel the request. /// <> - public async Task DeletePetAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task DeletePetAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await DeletePetWithHttpInfoAsync(petId, apiKey, cancellationToken).ConfigureAwait(false); @@ -625,6 +654,49 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (long, string?) OnDeletePet(long petId, string? apiKey) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, apiKey); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterDeletePet(ApiResponse apiResponse, long petId, string? apiKey) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorDeletePet(Exception exception, string pathFormat, string path, long petId, string? apiKey) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Deletes a pet /// @@ -635,29 +707,28 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeletePetWithHttpInfoAsync(long petId, string? apiKey = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (petId == null) - throw new ArgumentNullException(nameof(petId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnDeletePet(petId, apiKey); + petId = validatedParameters.Item1; + apiKey = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - if (apiKey != null) + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); if (apiKey != null) request.Headers.Add("api_key", ClientUtils.ParameterToString(apiKey)); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -668,28 +739,21 @@ namespace Org.OpenAPITools.Api request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeletePet(apiResponse, petId, apiKey); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -700,7 +764,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeletePet(e, "/pet/{petId}", uriBuilder.Path, petId, apiKey); throw; } } @@ -712,7 +776,7 @@ namespace Org.OpenAPITools.Api /// Status values that need to be considered for filter /// Cancellation Token to cancel the request. /// <> - public async Task?> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null) + public async Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse?> result = await FindPetsByStatusWithHttpInfoAsync(status, cancellationToken).ConfigureAwait(false); @@ -745,6 +809,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByStatus(List status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (status == null) + throw new ArgumentNullException(nameof(status)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return status; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByStatus(ApiResponse?> apiResponse, List status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByStatus(Exception exception, string pathFormat, string path, List status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by status Multiple status values can be provided with comma separated strings /// @@ -754,18 +858,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task?>> FindPetsByStatusWithHttpInfoAsync(List status, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (status == null) - throw new ArgumentNullException(nameof(status)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + status = OnFindPetsByStatus(status); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -779,6 +879,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -804,31 +906,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse?> apiResponse = new ApiResponse?>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByStatus(apiResponse, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -842,7 +937,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByStatus(e, "/pet/findByStatus", uriBuilder.Path, status); throw; } } @@ -854,7 +949,7 @@ namespace Org.OpenAPITools.Api /// Tags to filter by /// Cancellation Token to cancel the request. /// <> - public async Task?> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null) + public async Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse?> result = await FindPetsByTagsWithHttpInfoAsync(tags, cancellationToken).ConfigureAwait(false); @@ -887,6 +982,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByTags(List tags) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return tags; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByTags(ApiResponse?> apiResponse, List tags) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByTags(Exception exception, string pathFormat, string path, List tags) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @@ -896,18 +1031,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task?>> FindPetsByTagsWithHttpInfoAsync(List tags, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (tags == null) - throw new ArgumentNullException(nameof(tags)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + tags = OnFindPetsByTags(tags); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -921,6 +1052,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -946,31 +1079,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse?> apiResponse = new ApiResponse?>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByTags(apiResponse, tags); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -984,7 +1110,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByTags(e, "/pet/findByTags", uriBuilder.Path, tags); throw; } } @@ -996,7 +1122,7 @@ namespace Org.OpenAPITools.Api /// ID of pet to return /// Cancellation Token to cancel the request. /// <> - public async Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null) + public async Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await GetPetByIdWithHttpInfoAsync(petId, cancellationToken).ConfigureAwait(false); @@ -1029,6 +1155,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetPetById(long petId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return petId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetPetById(ApiResponse apiResponse, long petId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetPetById(Exception exception, string pathFormat, string path, long petId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find pet by ID Returns a single pet /// @@ -1038,25 +1204,20 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetPetByIdWithHttpInfoAsync(long petId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (petId == null) - throw new ArgumentNullException(nameof(petId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + petId = OnGetPetById(petId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokens = new List(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); List tokens = new List(); ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1075,31 +1236,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetPetById(apiResponse, petId); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1110,7 +1264,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetPetById(e, "/pet/{petId}", uriBuilder.Path, petId); throw; } } @@ -1122,7 +1276,7 @@ namespace Org.OpenAPITools.Api /// Pet object that needs to be added to the store /// Cancellation Token to cancel the request. /// <> - public async Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await UpdatePetWithHttpInfoAsync(pet, cancellationToken).ConfigureAwait(false); @@ -1155,6 +1309,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnUpdatePet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterUpdatePet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Update an existing pet /// @@ -1164,22 +1358,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnUpdatePet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress!.Host; - uriBuilder.Port = HttpClient.BaseAddress!.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -1187,6 +1377,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1211,32 +1403,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1250,7 +1435,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -1264,7 +1449,7 @@ namespace Org.OpenAPITools.Api /// Updated status of the pet (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UpdatePetWithFormAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdatePetWithFormAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await UpdatePetWithFormWithHttpInfoAsync(petId, name, status, cancellationToken).ConfigureAwait(false); @@ -1299,6 +1484,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, string?, string?) OnUpdatePetWithForm(long petId, string? name, string? status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, name, status); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUpdatePetWithForm(ApiResponse apiResponse, long petId, string? name, string? status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePetWithForm(Exception exception, string pathFormat, string path, long petId, string? name, string? status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updates a pet in the store with form data /// @@ -1310,33 +1541,29 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string? name = null, string? status = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (petId == null) - throw new ArgumentNullException(nameof(petId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdatePetWithForm(petId, name, status); + petId = validatedParameters.Item1; + name = validatedParameters.Item2; + status = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (name != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (name != null) formParams.Add(new KeyValuePair("name", ClientUtils.ParameterToString(name))); if (status != null) @@ -1344,6 +1571,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1359,32 +1588,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePetWithForm(apiResponse, petId, name, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1395,7 +1617,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePetWithForm(e, "/pet/{petId}", uriBuilder.Path, petId, name, status); throw; } } @@ -1405,13 +1627,13 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1424,16 +1646,16 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileOrDefaultAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileOrDefaultAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1444,51 +1666,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, System.IO.Stream?, string?) OnUploadFile(long petId, System.IO.Stream? file, string? additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, file, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFile(ApiResponse apiResponse, long petId, System.IO.Stream? file, string? additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFile(Exception exception, string pathFormat, string path, long petId, System.IO.Stream? file, string? additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UploadFileWithHttpInfoAsync(long petId, string? additionalMetadata = null, System.IO.Stream? file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream? file = null, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (petId == null) - throw new ArgumentNullException(nameof(petId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFile(petId, file, additionalMetadata); + petId = validatedParameters.Item1; + file = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}/uploadImage"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (file != null) + multipartContent.Add(new StreamContent(file)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); - if (file != null) - multipartContent.Add(new StreamContent(file)); - List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1504,7 +1770,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1514,31 +1780,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFile(apiResponse, petId, file, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1549,7 +1808,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFile(e, "/pet/{petId}/uploadImage", uriBuilder.Path, petId, file, additionalMetadata); throw; } } @@ -1558,14 +1817,14 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1577,17 +1836,17 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileOrDefaultAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1598,53 +1857,97 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (System.IO.Stream, long, string?) OnUploadFileWithRequiredFile(System.IO.Stream requiredFile, long petId, string? additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredFile == null) + throw new ArgumentNullException(nameof(requiredFile)); + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredFile, petId, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFileWithRequiredFile(ApiResponse apiResponse, System.IO.Stream requiredFile, long petId, string? additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFileWithRequiredFile(Exception exception, string pathFormat, string path, System.IO.Stream requiredFile, long petId, string? additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// 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> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string? additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (petId == null) - throw new ArgumentNullException(nameof(petId)); - - if (requiredFile == null) - throw new ArgumentNullException(nameof(requiredFile)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); + requiredFile = validatedParameters.Item1; + petId = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/{petId}/uploadImageWithRequiredFile"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - multipartContent.Add(new StreamContent(requiredFile)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); multipartContent.Add(new StreamContent(requiredFile)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1660,7 +1963,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json", @@ -1671,31 +1974,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFileWithRequiredFile(apiResponse, requiredFile, petId, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1706,8 +2002,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFileWithRequiredFile(e, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path, requiredFile, petId, additionalMetadata); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs index 1d07247d8e6..de9a6972e9e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IStoreApi : IApi { @@ -50,7 +51,7 @@ namespace Org.OpenAPITools.Api /// ID of the order that needs to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null); + Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null); /// /// Delete purchase order by ID @@ -63,7 +64,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task DeleteOrderOrDefaultAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null); - /// /// Returns pet inventories by status /// @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<Dictionary<string, int>> - Task?> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null); + Task> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null); /// /// Returns pet inventories by status @@ -96,7 +96,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<Dictionary<string, int>?> Task?> GetInventoryOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); - /// /// Find purchase order by ID /// @@ -119,7 +118,7 @@ namespace Org.OpenAPITools.Api /// ID of pet that needs to be fetched /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> - Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null); + Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null); /// /// Find purchase order by ID @@ -132,7 +131,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<Order?> Task GetOrderByIdOrDefaultAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null); - /// /// Place an order for a pet /// @@ -155,7 +153,7 @@ namespace Org.OpenAPITools.Api /// order placed for purchasing the pet /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> - Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); + Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); /// /// Place an order for a pet @@ -167,22 +165,18 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order?> Task PlaceOrderOrDefaultAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); + } +} - } - +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class StoreApi : IStoreApi + public partial class StoreApi : IApi.IStoreApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -239,6 +233,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -246,7 +249,7 @@ namespace Org.OpenAPITools.Api /// ID of the order that needs to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null) + public async Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await DeleteOrderWithHttpInfoAsync(orderId, cancellationToken).ConfigureAwait(false); @@ -279,6 +282,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteOrder(string orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteOrder(ApiResponse apiResponse, string orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteOrder(Exception exception, string pathFormat, string path, string orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -288,50 +331,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteOrderWithHttpInfoAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (orderId == null) - throw new ArgumentNullException(nameof(orderId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnDeleteOrder(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteOrder(apiResponse, orderId); + } return apiResponse; } @@ -339,7 +372,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteOrder(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -350,7 +383,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// <> - public async Task?> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null) + public async Task> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null) { ApiResponse?> result = await GetInventoryWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); @@ -382,6 +415,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetInventory() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetInventory(ApiResponse?> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetInventory(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// @@ -390,11 +451,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task?>> GetInventoryWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetInventory(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -418,31 +482,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse?> apiResponse = new ApiResponse?>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetInventory(apiResponse); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -453,7 +510,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetInventory(e, "/store/inventory", uriBuilder.Path); throw; } } @@ -465,7 +522,7 @@ namespace Org.OpenAPITools.Api /// ID of pet that needs to be fetched /// Cancellation Token to cancel the request. /// <> - public async Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null) + public async Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await GetOrderByIdWithHttpInfoAsync(orderId, cancellationToken).ConfigureAwait(false); @@ -498,6 +555,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetOrderById(long orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetOrderById(ApiResponse apiResponse, long orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetOrderById(Exception exception, string pathFormat, string path, long orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions /// @@ -507,22 +604,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetOrderByIdWithHttpInfoAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (orderId == null) - throw new ArgumentNullException(nameof(orderId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnGetOrderById(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; @@ -536,31 +630,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetOrderById(apiResponse, orderId); + } return apiResponse; } @@ -568,7 +655,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetOrderById(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -580,7 +667,7 @@ namespace Org.OpenAPITools.Api /// order placed for purchasing the pet /// Cancellation Token to cancel the request. /// <> - public async Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null) + public async Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await PlaceOrderWithHttpInfoAsync(order, cancellationToken).ConfigureAwait(false); @@ -613,6 +700,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Order OnPlaceOrder(Order order) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (order == null) + throw new ArgumentNullException(nameof(order)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return order; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterPlaceOrder(ApiResponse apiResponse, Order order) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorPlaceOrder(Exception exception, string pathFormat, string path, Order order) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Place an order for a pet /// @@ -622,18 +749,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> PlaceOrderWithHttpInfoAsync(Order order, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (order == null) - throw new ArgumentNullException(nameof(order)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + order = OnPlaceOrder(order); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -643,6 +766,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(order, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -652,7 +777,7 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/xml", @@ -663,31 +788,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterPlaceOrder(apiResponse, order); + } return apiResponse; } @@ -695,8 +813,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorPlaceOrder(e, "/store/order", uriBuilder.Path, order); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs index 1d51468c105..d6d3548d8aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs @@ -21,10 +21,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IUserApi : IApi { @@ -50,7 +51,7 @@ namespace Org.OpenAPITools.Api /// Created user object /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null); + Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null); /// /// Create user @@ -63,7 +64,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task CreateUserOrDefaultAsync(User user, System.Threading.CancellationToken? cancellationToken = null); - /// /// Creates list of users with given input array /// @@ -86,7 +86,7 @@ namespace Org.OpenAPITools.Api /// List of user object /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); /// /// Creates list of users with given input array @@ -99,7 +99,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task CreateUsersWithArrayInputOrDefaultAsync(List user, System.Threading.CancellationToken? cancellationToken = null); - /// /// Creates list of users with given input array /// @@ -122,7 +121,7 @@ namespace Org.OpenAPITools.Api /// List of user object /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); /// /// Creates list of users with given input array @@ -135,7 +134,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task CreateUsersWithListInputOrDefaultAsync(List user, System.Threading.CancellationToken? cancellationToken = null); - /// /// Delete user /// @@ -158,7 +156,7 @@ namespace Org.OpenAPITools.Api /// The name that needs to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Delete user @@ -171,7 +169,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task DeleteUserOrDefaultAsync(string username, System.Threading.CancellationToken? cancellationToken = null); - /// /// Get user by user name /// @@ -194,7 +191,7 @@ namespace Org.OpenAPITools.Api /// The name that needs to be fetched. Use user1 for testing. /// Cancellation Token to cancel the request. /// Task of ApiResponse<User> - Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Get user by user name @@ -207,7 +204,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<User?> Task GetUserByNameOrDefaultAsync(string username, System.Threading.CancellationToken? cancellationToken = null); - /// /// Logs user into the system /// @@ -232,7 +228,7 @@ namespace Org.OpenAPITools.Api /// The password for login in clear text /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> - Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null); + Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null); /// /// Logs user into the system @@ -246,7 +242,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<string?> Task LoginUserOrDefaultAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null); - /// /// Logs out current logged in user session /// @@ -267,7 +262,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null); + Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null); /// /// Logs out current logged in user session @@ -279,7 +274,6 @@ namespace Org.OpenAPITools.Api /// Task of ApiResponse<object?> Task LogoutUserOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); - /// /// Updated user /// @@ -287,11 +281,11 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task<ApiResponse<object?>> - Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); + Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Updated user @@ -300,11 +294,11 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); + Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Updated user @@ -312,27 +306,23 @@ namespace Org.OpenAPITools.Api /// /// This can only be done by the logged in user. /// - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object?> - Task UpdateUserOrDefaultAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); - - } + Task UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class UserApi : IUserApi + public partial class UserApi : IApi.IUserApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler? ApiResponded; - /// /// The logger /// @@ -389,6 +379,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Create user This can only be done by the logged in user. /// @@ -396,7 +395,7 @@ namespace Org.OpenAPITools.Api /// Created user object /// Cancellation Token to cancel the request. /// <> - public async Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await CreateUserWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); @@ -429,6 +428,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual User OnCreateUser(User user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUser(ApiResponse apiResponse, User user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUser(Exception exception, string pathFormat, string path, User user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Create user This can only be done by the logged in user. /// @@ -438,18 +477,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUserWithHttpInfoAsync(User user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUser(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -459,6 +494,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -468,32 +505,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUser(apiResponse, user); + } return apiResponse; } @@ -501,7 +531,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUser(e, "/user", uriBuilder.Path, user); throw; } } @@ -513,7 +543,7 @@ namespace Org.OpenAPITools.Api /// List of user object /// Cancellation Token to cancel the request. /// <> - public async Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null) + public async Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await CreateUsersWithArrayInputWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); @@ -546,6 +576,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithArrayInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithArrayInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithArrayInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -555,18 +625,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithArrayInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -576,6 +642,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -585,32 +653,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithArrayInput(apiResponse, user); + } return apiResponse; } @@ -618,7 +679,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithArrayInput(e, "/user/createWithArray", uriBuilder.Path, user); throw; } } @@ -630,7 +691,7 @@ namespace Org.OpenAPITools.Api /// List of user object /// Cancellation Token to cancel the request. /// <> - public async Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null) + public async Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await CreateUsersWithListInputWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); @@ -663,6 +724,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithListInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithListInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithListInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -672,18 +773,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithListInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithListInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -693,6 +790,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -702,32 +801,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithListInput(apiResponse, user); + } return apiResponse; } @@ -735,7 +827,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithListInput(e, "/user/createWithList", uriBuilder.Path, user); throw; } } @@ -747,7 +839,7 @@ namespace Org.OpenAPITools.Api /// The name that needs to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null) + public async Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await DeleteUserWithHttpInfoAsync(username, cancellationToken).ConfigureAwait(false); @@ -780,6 +872,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteUser(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteUser(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteUser(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete user This can only be done by the logged in user. /// @@ -789,50 +921,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteUserWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnDeleteUser(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteUser(apiResponse, username); + } return apiResponse; } @@ -840,7 +962,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteUser(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -852,7 +974,7 @@ namespace Org.OpenAPITools.Api /// The name that needs to be fetched. Use user1 for testing. /// Cancellation Token to cancel the request. /// <> - public async Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null) + public async Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await GetUserByNameWithHttpInfoAsync(username, cancellationToken).ConfigureAwait(false); @@ -885,6 +1007,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnGetUserByName(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetUserByName(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetUserByName(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Get user by user name /// @@ -894,22 +1056,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetUserByNameWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnGetUserByName(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; @@ -923,31 +1082,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetUserByName(apiResponse, username); + } return apiResponse; } @@ -955,7 +1107,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetUserByName(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -968,7 +1120,7 @@ namespace Org.OpenAPITools.Api /// The password for login in clear text /// Cancellation Token to cancel the request. /// <> - public async Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null) + public async Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await LoginUserWithHttpInfoAsync(username, password, cancellationToken).ConfigureAwait(false); @@ -1002,6 +1154,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnLoginUser(string username, string password) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + if (password == null) + throw new ArgumentNullException(nameof(password)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (username, password); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterLoginUser(ApiResponse apiResponse, string username, string password) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorLoginUser(Exception exception, string pathFormat, string path, string username, string password) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs user into the system /// @@ -1012,21 +1210,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LoginUserWithHttpInfoAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (password == null) - throw new ArgumentNullException(nameof(password)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnLoginUser(username, password); + username = validatedParameters.Item1; + password = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1039,6 +1232,8 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -1050,31 +1245,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLoginUser(apiResponse, username, password); + } return apiResponse; } @@ -1082,7 +1270,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLoginUser(e, "/user/login", uriBuilder.Path, username, password); throw; } } @@ -1093,7 +1281,7 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// <> - public async Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null) + public async Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = await LogoutUserWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); @@ -1125,6 +1313,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnLogoutUser() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterLogoutUser(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorLogoutUser(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs out current logged in user session /// @@ -1133,42 +1349,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LogoutUserWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnLogoutUser(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/logout"; + + request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLogoutUser(apiResponse); + } return apiResponse; } @@ -1176,7 +1390,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLogoutUser(e, "/user/logout", uriBuilder.Path); throw; } } @@ -1185,13 +1399,13 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1203,16 +1417,16 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserOrDefaultAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse? result = null; try { - result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1223,41 +1437,83 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnUpdateUser(User user, string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, username); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterUpdateUser(ApiResponse apiResponse, User user, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdateUser(Exception exception, string pathFormat, string path, User user, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdateUser(user, username); + user = validatedParameters.Item1; + username = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress!.Host; uriBuilder.Port = HttpClient.BaseAddress!.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); - request.Content = (user as object) is System.IO.Stream stream + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.Content = (user as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1267,32 +1523,25 @@ namespace Org.OpenAPITools.Api string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdateUser(apiResponse, user, username); + } return apiResponse; } @@ -1300,8 +1549,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdateUser(e, "/user/{username}", uriBuilder.Path, user, username); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 00000000000..7757b89c191 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.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.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs index 32793bac5cc..a421f4e53e6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -18,22 +18,12 @@ namespace Org.OpenAPITools.Client /// /// /// - /// + /// public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { _raw = $"{ prefix }{ value }"; } - /// - /// Places the token in the cookie. - /// - /// - /// - public virtual void UseInCookie(System.Net.Http.HttpRequestMessage request, string cookieName) - { - request.Headers.Add("Cookie", $"{ cookieName }=_raw"); - } - /// /// Places the token in the header. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs index e5da6000321..f87e53e8b04 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -12,35 +12,46 @@ namespace Org.OpenAPITools.Client /// The time the request was sent. /// public DateTime RequestedAt { get; } + /// /// The time the response was received. /// public DateTime ReceivedAt { get; } + /// /// The HttpStatusCode received. /// public HttpStatusCode HttpStatus { get; } + /// /// The path requested. /// - public string Path { get; } + public string PathFormat { get; } + /// /// The elapsed time from request to response. /// public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + /// + /// The path + /// + public string Path { get; } + /// /// The event args used to track server health. /// /// /// /// + /// /// - public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string path) + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) { RequestedAt = requestedAt; ReceivedAt = receivedAt; HttpStatus = httpStatus; + PathFormat = pathFormat; Path = path; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs index 36696f85be3..1148457b2b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -36,6 +36,11 @@ namespace Org.OpenAPITools.Client /// The raw content of this response /// string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } } /// @@ -43,12 +48,10 @@ namespace Org.OpenAPITools.Client /// public partial class ApiResponse : IApiResponse { - #region Properties - /// /// The deserialized content /// - public T? Content { get; set; } + public T? Content { get; internal set; } /// /// Gets or sets the status code (HTTP status code) @@ -84,7 +87,10 @@ namespace Org.OpenAPITools.Client /// public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } - #endregion Properties + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; /// /// Construct the response using an HttpResponseMessage diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs index 73d48918517..e23f5314802 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -12,16 +12,9 @@ using System; using System.IO; using System.Linq; -using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Polly.Timeout; -using Polly.Extensions.Http; -using Polly; -using Org.OpenAPITools.Api; using KellermanSoftware.CompareNetObjects; namespace Org.OpenAPITools.Client @@ -282,114 +275,5 @@ namespace Org.OpenAPITools.Client /// The format to use for DateTime serialization /// public const string ISO8601_DATETIME_FORMAT = "o"; - - /// - /// 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, config); - - AddApi(services, config); - }); - - return builder; - } - - /// - /// Add the api to your host builder. - /// - /// - /// - public static void AddApi(this IServiceCollection services, Action options) - { - HostConfiguration config = new HostConfiguration(services); - options(config); - AddApi(services, config); - } - - private static void AddApi(IServiceCollection services, HostConfiguration host) - { - if (!host.HttpClientsAdded) - host.AddApiHttpClients(); - - // 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))); - } - } - } - - /// - /// 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 circiut 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 00000000000..85093b0c1fe --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 00000000000..a86c694664d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * 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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 00000000000..abf780dcd83 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs index d0346cfb491..4583545e96c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -16,7 +16,6 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Net.Http; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client @@ -24,10 +23,17 @@ namespace Org.OpenAPITools.Client /// /// Provides hosting configuration for Org.OpenAPITools /// - public class HostConfiguration + public class HostConfiguration + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi { private readonly IServiceCollection _services; - private JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); internal bool HttpClientsAdded { get; private set; } @@ -39,35 +45,101 @@ namespace Org.OpenAPITools.Client { _services = services; _jsonOptions.Converters.Add(new JsonStringEnumConverter()); - _jsonOptions.Converters.Add(new OpenAPIDateJsonConverter()); + _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 CatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new CategoryJsonConverter()); _jsonOptions.Converters.Add(new ChildCatJsonConverter()); + _jsonOptions.Converters.Add(new ChildCatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new ClassModelJsonConverter()); _jsonOptions.Converters.Add(new ComplexQuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new DanishPigJsonConverter()); + _jsonOptions.Converters.Add(new DeprecatedObjectJsonConverter()); _jsonOptions.Converters.Add(new DogJsonConverter()); + _jsonOptions.Converters.Add(new DogAllOfJsonConverter()); + _jsonOptions.Converters.Add(new DrawingJsonConverter()); + _jsonOptions.Converters.Add(new EnumArraysJsonConverter()); + _jsonOptions.Converters.Add(new EnumClassConverter()); + _jsonOptions.Converters.Add(new EnumClassNullableConverter()); + _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 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 NullableClassJsonConverter()); _jsonOptions.Converters.Add(new NullableShapeJsonConverter()); + _jsonOptions.Converters.Add(new NumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ObjectWithDeprecatedFieldsJsonConverter()); + _jsonOptions.Converters.Add(new OrderJsonConverter()); + _jsonOptions.Converters.Add(new OuterCompositeJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumConverter()); + _jsonOptions.Converters.Add(new OuterEnumNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueNullableConverter()); _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 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 TriangleJsonConverter()); + _jsonOptions.Converters.Add(new TriangleInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new WhaleJsonConverter()); + _jsonOptions.Converters.Add(new ZebraJsonConverter()); _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); } /// @@ -76,29 +148,22 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddApiHttpClients + public HostConfiguration AddApiHttpClients ( Action? client = null, Action? builder = null) - where TAnotherFakeApi : class, IAnotherFakeApi - where TDefaultApi : class, IDefaultApi - where TFakeApi : class, IFakeApi - where TFakeClassnameTags123Api : class, IFakeClassnameTags123Api - where TPetApi : class, IPetApi - where TStoreApi : class, IStoreApi - where TUserApi : class, IUserApi { 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)); + + 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) @@ -109,25 +174,12 @@ namespace Org.OpenAPITools.Client return this; } - /// - /// Configures the HttpClients. - /// - /// - /// - /// - public HostConfiguration AddApiHttpClients(Action? client = null, Action? builder = null) - { - AddApiHttpClients(client, builder); - - return this; - } - /// /// Configures the JsonSerializerSettings /// /// /// - public HostConfiguration ConfigureJsonOptions(Action options) + public HostConfiguration ConfigureJsonOptions(Action options) { options(_jsonOptions); @@ -140,7 +192,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase { return AddTokens(new TTokenBase[]{ token }); } @@ -151,7 +203,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase { TokenContainer container = new TokenContainer(tokens); _services.AddSingleton(services => container); @@ -165,7 +217,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration UseProvider() + public HostConfiguration UseProvider() where TTokenProvider : TokenProvider where TTokenBase : TokenBase { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/IApi.cs deleted file mode 100644 index 53c5a858ffa..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/IApi.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Net.Http; - -namespace Org.OpenAPITools.Client -{ - /// - /// Any Api client - /// - public interface IApi - { - /// - /// The HttpClient - /// - HttpClient HttpClient { get; } - - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - event ClientUtils.EventHandler? ApiResponded; - } -} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs deleted file mode 100644 index 5f64123b7d5..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 Org.OpenAPITools.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 OpenAPIDateJsonConverter : JsonConverter - { - /// - /// Returns a DateTime from the Json object - /// - /// - /// - /// - /// - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => - DateTime.ParseExact(reader.GetString()!, "yyyy-MM-dd", CultureInfo.InvariantCulture); - - /// - /// Writes the DateTime to the json writer - /// - /// - /// - /// - public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => - writer.WriteStringValue(dateTimeValue.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); - } -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 00000000000..798c676b1bb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,59 @@ +/* + * 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 Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 00000000000..95cbdb38088 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/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 Org.OpenAPITools.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 circiut 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 00000000000..1ed9bbd90ad --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,90 @@ +/* + * 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 Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + 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-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs index d8753f6553e..3e658cad4d1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// test map of maps /// - public partial class Activity : IEquatable, IValidatableObject + public partial class Activity : IValidatableObject { /// /// Initializes a new instance of the class. /// /// activityOutputs - public Activity(Dictionary>? activityOutputs = default) + [JsonConstructor] + public Activity(Dictionary> activityOutputs) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (activityOutputs == null) + throw new ArgumentNullException("activityOutputs is a required property for Activity and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ActivityOutputs = activityOutputs; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets ActivityOutputs /// [JsonPropertyName("activity_outputs")] - public Dictionary>? ActivityOutputs { get; set; } + public Dictionary> ActivityOutputs { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 Activity).AreEqual; - } - - /// - /// Returns true if Activity instances are equal - /// - /// Instance of Activity to be compared - /// Boolean - public bool Equals(Activity? 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; - if (this.ActivityOutputs != null) - { - hashCode = (hashCode * 59) + this.ActivityOutputs.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Activity + /// + public class ActivityJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Activity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary> activityOutputs = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "activity_outputs": + activityOutputs = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new Activity(activityOutputs); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Activity activity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index 2cd5bb9372e..3cfe6229889 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// ActivityOutputElementRepresentation /// - public partial class ActivityOutputElementRepresentation : IEquatable, IValidatableObject + public partial class ActivityOutputElementRepresentation : IValidatableObject { /// /// Initializes a new instance of the class. /// /// prop1 /// prop2 - public ActivityOutputElementRepresentation(string? prop1 = default, Object? prop2 = default) + [JsonConstructor] + public ActivityOutputElementRepresentation(string prop1, Object prop2) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (prop1 == null) + throw new ArgumentNullException("prop1 is a required property for ActivityOutputElementRepresentation and cannot be null."); + + if (prop2 == null) + throw new ArgumentNullException("prop2 is a required property for ActivityOutputElementRepresentation and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Prop1 = prop1; Prop2 = prop2; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Prop1 /// [JsonPropertyName("prop1")] - public string? Prop1 { get; set; } + public string Prop1 { get; set; } /// /// Gets or Sets Prop2 /// [JsonPropertyName("prop2")] - public Object? Prop2 { get; set; } + public Object Prop2 { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,52 +86,6 @@ namespace Org.OpenAPITools.Model 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 ActivityOutputElementRepresentation).AreEqual; - } - - /// - /// Returns true if ActivityOutputElementRepresentation instances are equal - /// - /// Instance of ActivityOutputElementRepresentation to be compared - /// Boolean - public bool Equals(ActivityOutputElementRepresentation? 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; - if (this.Prop1 != null) - { - hashCode = (hashCode * 59) + this.Prop1.GetHashCode(); - } - if (this.Prop2 != null) - { - hashCode = (hashCode * 59) + this.Prop2.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -131,4 +97,77 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ActivityOutputElementRepresentation + /// + public class ActivityOutputElementRepresentationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string prop1 = default; + Object prop2 = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "prop1": + prop1 = reader.GetString(); + break; + case "prop2": + prop2 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new ActivityOutputElementRepresentation(prop1, prop2); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 6525a4a0348..2bdee7f21c5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,42 +28,101 @@ namespace Org.OpenAPITools.Model /// /// AdditionalPropertiesClass /// - public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class AdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty - /// anytype1 + /// mapProperty /// mapWithUndeclaredPropertiesAnytype1 /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 - /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapWithUndeclaredPropertiesString - public AdditionalPropertiesClass(Dictionary? mapProperty = default, Dictionary>? mapOfMapProperty = default, Object? anytype1 = default, Object? mapWithUndeclaredPropertiesAnytype1 = default, Object? mapWithUndeclaredPropertiesAnytype2 = default, Dictionary? mapWithUndeclaredPropertiesAnytype3 = default, Object? emptyMap = default, Dictionary? mapWithUndeclaredPropertiesString = default) + /// anytype1 + [JsonConstructor] + public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object? anytype1 = default) { - MapProperty = mapProperty; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapProperty == null) + throw new ArgumentNullException("mapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapOfMapProperty == null) + throw new ArgumentNullException("mapOfMapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype1 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype2 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype3 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (emptyMap == null) + throw new ArgumentNullException("emptyMap is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesString is a required property for AdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + EmptyMap = emptyMap; MapOfMapProperty = mapOfMapProperty; - Anytype1 = anytype1; + MapProperty = mapProperty; MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - EmptyMap = emptyMap; MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + Anytype1 = anytype1; } /// - /// Gets or Sets MapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// - [JsonPropertyName("map_property")] - public Dictionary? MapProperty { get; set; } + /// 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; } + 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 @@ -72,42 +130,11 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("anytype_1")] public Object? Anytype1 { 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; } - - /// - /// 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 MapWithUndeclaredPropertiesString - /// - [JsonPropertyName("map_with_undeclared_properties_string")] - public Dictionary? MapWithUndeclaredPropertiesString { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -117,88 +144,18 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); - sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).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(" EmptyMap: ").Append(EmptyMap).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesClass instances are equal - /// - /// Instance of AdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(AdditionalPropertiesClass? 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; - if (this.MapProperty != null) - { - hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); - } - if (this.MapOfMapProperty != null) - { - hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); - } - if (this.Anytype1 != null) - { - hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype1 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype2 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype3 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); - } - if (this.EmptyMap != null) - { - hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesString != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -210,4 +167,114 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AdditionalPropertiesClass + /// + public class AdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "empty_map": + emptyMap = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_of_map_property": + mapOfMapProperty = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_property": + mapProperty = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_1": + mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_2": + mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_3": + mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_string": + mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref reader, options); + break; + case "anytype_1": + anytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, options); + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, options); + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, options); + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, options); + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs index 21aa789d306..8d5bd4c6c90 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,18 +28,28 @@ namespace Org.OpenAPITools.Model /// /// Animal /// - public partial class Animal : IEquatable, IValidatableObject + public partial class Animal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// color (default to "red") - public Animal(string className, string? color = "red") + [JsonConstructor] + public Animal(string className, string color = "red") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for Animal and cannot be null."); + if (color == null) + throw new ArgumentNullException("color is a required property for Animal and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Color = color; } @@ -55,13 +64,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Color /// [JsonPropertyName("color")] - public string? Color { get; set; } + public string Color { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -77,52 +86,6 @@ namespace Org.OpenAPITools.Model 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 Animal).AreEqual; - } - - /// - /// Returns true if Animal instances are equal - /// - /// Instance of Animal to be compared - /// Boolean - public bool Equals(Animal? 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -144,4 +107,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Animal + /// + public class AnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + string color = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "color": + color = reader.GetString(); + break; + default: + break; + } + } + } + + return new Animal(className, color); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", animal.ClassName); + writer.WriteString("color", animal.Color); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs index 8bde19180cb..ca44ce608dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,44 +28,60 @@ namespace Org.OpenAPITools.Model /// /// ApiResponse /// - public partial class ApiResponse : IEquatable, IValidatableObject + public partial class ApiResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// /// code - /// type /// message - public ApiResponse(int? code = default, string? type = default, string? message = default) + /// type + [JsonConstructor] + public ApiResponse(int code, string message, string type) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (code == null) + throw new ArgumentNullException("code is a required property for ApiResponse and cannot be null."); + + if (type == null) + throw new ArgumentNullException("type is a required property for ApiResponse and cannot be null."); + + if (message == null) + throw new ArgumentNullException("message is a required property for ApiResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Code = code; - Type = type; Message = message; + Type = type; } /// /// Gets or Sets Code /// [JsonPropertyName("code")] - public int? Code { get; set; } - - /// - /// Gets or Sets Type - /// - [JsonPropertyName("type")] - public string? Type { get; set; } + public int Code { get; set; } /// /// Gets or Sets Message /// [JsonPropertyName("message")] - public string? Message { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -77,59 +92,12 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); - sb.Append(" Type: ").Append(Type).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ApiResponse).AreEqual; - } - - /// - /// Returns true if ApiResponse instances are equal - /// - /// Instance of ApiResponse to be compared - /// Boolean - public bool Equals(ApiResponse? 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) + this.Code.GetHashCode(); - if (this.Type != null) - { - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - } - if (this.Message != null) - { - hashCode = (hashCode * 59) + this.Message.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,4 +109,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ApiResponse + /// + public class ApiResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ApiResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int code = default; + string message = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "code": + code = reader.GetInt32(); + break; + case "message": + message = reader.GetString(); + break; + case "type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new ApiResponse(code, message, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("code", (int)apiResponse.Code); + writer.WriteString("message", apiResponse.Message); + writer.WriteString("type", apiResponse.Type); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs index dadf5664d05..bd710804c00 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// Apple /// - public partial class Apple : IEquatable, IValidatableObject + public partial class Apple : IValidatableObject { /// /// Initializes a new instance of the class. /// /// cultivar /// origin - public Apple(string? cultivar = default, string? origin = default) + [JsonConstructor] + public Apple(string cultivar, string origin) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (cultivar == null) + throw new ArgumentNullException("cultivar is a required property for Apple and cannot be null."); + + if (origin == null) + throw new ArgumentNullException("origin is a required property for Apple and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Origin = origin; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Cultivar /// [JsonPropertyName("cultivar")] - public string? Cultivar { get; set; } + public string Cultivar { get; set; } /// /// Gets or Sets Origin /// [JsonPropertyName("origin")] - public string? Origin { get; set; } + public string Origin { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,52 +86,6 @@ namespace Org.OpenAPITools.Model 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 Apple).AreEqual; - } - - /// - /// Returns true if Apple instances are equal - /// - /// Instance of Apple to be compared - /// Boolean - public bool Equals(Apple? 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - if (this.Origin != null) - { - hashCode = (hashCode * 59) + this.Origin.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -145,4 +111,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Apple + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + string origin = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "origin": + origin = reader.GetString(); + break; + default: + break; + } + } + } + + return new Apple(cultivar, origin); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", apple.Cultivar); + writer.WriteString("origin", apple.Origin); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs index d323a03e068..93a9e8fb3d7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,18 +28,28 @@ namespace Org.OpenAPITools.Model /// /// AppleReq /// - public partial class AppleReq : IEquatable, IValidatableObject + public partial class AppleReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// cultivar (required) + /// cultivar /// mealy - public AppleReq(string cultivar, bool? mealy = default) + [JsonConstructor] + public AppleReq(string cultivar, bool mealy) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (cultivar == null) throw new ArgumentNullException("cultivar is a required property for AppleReq and cannot be null."); + if (mealy == null) + throw new ArgumentNullException("mealy is a required property for AppleReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Mealy = mealy; } @@ -55,7 +64,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Mealy /// [JsonPropertyName("mealy")] - public bool? Mealy { get; set; } + public bool Mealy { get; set; } /// /// Returns the string presentation of the object @@ -70,45 +79,6 @@ namespace Org.OpenAPITools.Model 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 AppleReq).AreEqual; - } - - /// - /// Returns true if AppleReq instances are equal - /// - /// Instance of AppleReq to be compared - /// Boolean - public bool Equals(AppleReq? 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -120,4 +90,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AppleReq + /// + public class AppleReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AppleReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + bool mealy = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "mealy": + mealy = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new AppleReq(cultivar, mealy); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", appleReq.Cultivar); + writer.WriteBoolean("mealy", appleReq.Mealy); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index e284a52634b..f59cb185498 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfArrayOfNumberOnly /// - public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayArrayNumber - public ArrayOfArrayOfNumberOnly(List>? arrayArrayNumber = default) + [JsonConstructor] + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayArrayNumber == null) + throw new ArgumentNullException("arrayArrayNumber is a required property for ArrayOfArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayNumber = arrayArrayNumber; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets ArrayArrayNumber /// [JsonPropertyName("ArrayArrayNumber")] - public List>? ArrayArrayNumber { get; set; } + public List> ArrayArrayNumber { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfArrayOfNumberOnly? 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; - if (this.ArrayArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfArrayOfNumberOnly + /// + public class ArrayOfArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayArrayNumber": + arrayArrayNumber = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 1670dcd31a3..58c27adc71d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfNumberOnly /// - public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayNumber - public ArrayOfNumberOnly(List? arrayNumber = default) + [JsonConstructor] + public ArrayOfNumberOnly(List arrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayNumber == null) + throw new ArgumentNullException("arrayNumber is a required property for ArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayNumber = arrayNumber; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets ArrayNumber /// [JsonPropertyName("ArrayNumber")] - public List? ArrayNumber { get; set; } + public List ArrayNumber { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfNumberOnly? 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; - if (this.ArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfNumberOnly + /// + public class ArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayNumber": + arrayNumber = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfNumberOnly(arrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs index 371238a32a6..95286c8847a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,44 +28,60 @@ namespace Org.OpenAPITools.Model /// /// ArrayTest /// - public partial class ArrayTest : IEquatable, IValidatableObject + public partial class ArrayTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayOfString /// arrayArrayOfInteger /// arrayArrayOfModel - public ArrayTest(List? arrayOfString = default, List>? arrayArrayOfInteger = default, List>? arrayArrayOfModel = default) + /// arrayOfString + [JsonConstructor] + public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) { - ArrayOfString = arrayOfString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayOfString == null) + throw new ArgumentNullException("arrayOfString is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfInteger == null) + throw new ArgumentNullException("arrayArrayOfInteger is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfModel == null) + throw new ArgumentNullException("arrayArrayOfModel is a required property for ArrayTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayOfInteger = arrayArrayOfInteger; ArrayArrayOfModel = arrayArrayOfModel; + ArrayOfString = arrayOfString; } - /// - /// Gets or Sets ArrayOfString - /// - [JsonPropertyName("array_of_string")] - public List? ArrayOfString { get; set; } - /// /// Gets or Sets ArrayArrayOfInteger /// [JsonPropertyName("array_array_of_integer")] - public List>? ArrayArrayOfInteger { get; set; } + public List> ArrayArrayOfInteger { get; set; } /// /// Gets or Sets ArrayArrayOfModel /// [JsonPropertyName("array_array_of_model")] - public List>? ArrayArrayOfModel { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -76,63 +91,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); - sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayTest).AreEqual; - } - - /// - /// Returns true if ArrayTest instances are equal - /// - /// Instance of ArrayTest to be compared - /// Boolean - public bool Equals(ArrayTest? 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; - if (this.ArrayOfString != null) - { - hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); - } - if (this.ArrayArrayOfInteger != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); - } - if (this.ArrayArrayOfModel != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -144,4 +109,84 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayTest + /// + public class ArrayTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayOfInteger = default; + List> arrayArrayOfModel = default; + List arrayOfString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_array_of_integer": + arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_array_of_model": + arrayArrayOfModel = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_of_string": + arrayOfString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, options); + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, options); + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs index d41ec32c1d8..736cd0de7bc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// Banana /// - public partial class Banana : IEquatable, IValidatableObject + public partial class Banana : IValidatableObject { /// /// Initializes a new instance of the class. /// /// lengthCm - public Banana(decimal? lengthCm = default) + [JsonConstructor] + public Banana(decimal lengthCm) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (lengthCm == null) + throw new ArgumentNullException("lengthCm is a required property for Banana and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets LengthCm /// [JsonPropertyName("lengthCm")] - public decimal? LengthCm { get; set; } + public decimal LengthCm { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,45 +74,6 @@ namespace Org.OpenAPITools.Model 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 Banana).AreEqual; - } - - /// - /// Returns true if Banana instances are equal - /// - /// Instance of Banana to be compared - /// Boolean - public bool Equals(Banana? 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) + this.LengthCm.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Banana + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Banana(lengthCm); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)banana.LengthCm); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs index cd3eaea9483..cd32083c6be 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,18 +28,28 @@ namespace Org.OpenAPITools.Model /// /// BananaReq /// - public partial class BananaReq : IEquatable, IValidatableObject + public partial class BananaReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// lengthCm (required) + /// lengthCm /// sweet - public BananaReq(decimal lengthCm, bool? sweet = default) + [JsonConstructor] + public BananaReq(decimal lengthCm, bool sweet) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (lengthCm == null) throw new ArgumentNullException("lengthCm is a required property for BananaReq and cannot be null."); + if (sweet == null) + throw new ArgumentNullException("sweet is a required property for BananaReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; Sweet = sweet; } @@ -55,7 +64,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Sweet /// [JsonPropertyName("sweet")] - public bool? Sweet { get; set; } + public bool Sweet { get; set; } /// /// Returns the string presentation of the object @@ -70,42 +79,6 @@ namespace Org.OpenAPITools.Model 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 BananaReq).AreEqual; - } - - /// - /// Returns true if BananaReq instances are equal - /// - /// Instance of BananaReq to be compared - /// Boolean - public bool Equals(BananaReq? 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) + this.LengthCm.GetHashCode(); - hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -117,4 +90,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BananaReq + /// + public class BananaReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BananaReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + bool sweet = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + case "sweet": + sweet = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new BananaReq(lengthCm, sweet); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)bananaReq.LengthCm); + writer.WriteBoolean("sweet", bananaReq.Sweet); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs index 4f846443361..bd29e866057 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// BasquePig /// - public partial class BasquePig : IEquatable, IValidatableObject + public partial class BasquePig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public BasquePig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for BasquePig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 BasquePig).AreEqual; - } - - /// - /// Returns true if BasquePig instances are equal - /// - /// Instance of BasquePig to be compared - /// Boolean - public bool Equals(BasquePig? 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -121,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BasquePig + /// + public class BasquePigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BasquePig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new BasquePig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", basquePig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs index 2a52a362f69..7b2728c1e73 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,69 +28,94 @@ namespace Org.OpenAPITools.Model /// /// Capitalization /// - public partial class Capitalization : IEquatable, IValidatableObject + public partial class Capitalization : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// smallCamel + /// Name of the pet /// capitalCamel - /// smallSnake /// capitalSnake /// sCAETHFlowPoints - /// Name of the pet - public Capitalization(string? smallCamel = default, string? capitalCamel = default, string? smallSnake = default, string? capitalSnake = default, string? sCAETHFlowPoints = default, string? aTTNAME = default) + /// smallCamel + /// smallSnake + [JsonConstructor] + public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) { - SmallCamel = smallCamel; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (smallCamel == null) + throw new ArgumentNullException("smallCamel is a required property for Capitalization and cannot be null."); + + if (capitalCamel == null) + throw new ArgumentNullException("capitalCamel is a required property for Capitalization and cannot be null."); + + if (smallSnake == null) + throw new ArgumentNullException("smallSnake is a required property for Capitalization and cannot be null."); + + if (capitalSnake == null) + throw new ArgumentNullException("capitalSnake is a required property for Capitalization and cannot be null."); + + if (sCAETHFlowPoints == null) + throw new ArgumentNullException("sCAETHFlowPoints is a required property for Capitalization and cannot be null."); + + if (aTTNAME == null) + throw new ArgumentNullException("aTTNAME is a required property for Capitalization and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ATT_NAME = aTTNAME; CapitalCamel = capitalCamel; - SmallSnake = smallSnake; CapitalSnake = capitalSnake; SCAETHFlowPoints = sCAETHFlowPoints; - ATT_NAME = aTTNAME; + SmallCamel = smallCamel; + SmallSnake = smallSnake; } - /// - /// Gets or Sets SmallCamel - /// - [JsonPropertyName("smallCamel")] - public string? SmallCamel { get; set; } - - /// - /// Gets or Sets CapitalCamel - /// - [JsonPropertyName("CapitalCamel")] - public string? CapitalCamel { get; set; } - - /// - /// Gets or Sets SmallSnake - /// - [JsonPropertyName("small_Snake")] - public string? SmallSnake { 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; } - /// /// Name of the pet /// /// Name of the pet [JsonPropertyName("ATT_NAME")] - public string? ATT_NAME { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -101,78 +125,16 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); - sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); - sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); - sb.Append(" ATT_NAME: ").Append(ATT_NAME).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Capitalization).AreEqual; - } - - /// - /// Returns true if Capitalization instances are equal - /// - /// Instance of Capitalization to be compared - /// Boolean - public bool Equals(Capitalization? 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; - if (this.SmallCamel != null) - { - hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); - } - if (this.CapitalCamel != null) - { - hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); - } - if (this.SmallSnake != null) - { - hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); - } - if (this.CapitalSnake != null) - { - hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); - } - if (this.SCAETHFlowPoints != null) - { - hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); - } - if (this.ATT_NAME != null) - { - hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -184,4 +146,96 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Capitalization + /// + public class CapitalizationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Capitalization Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string aTTNAME = default; + string capitalCamel = default; + string capitalSnake = default; + string sCAETHFlowPoints = default; + string smallCamel = default; + string smallSnake = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ATT_NAME": + aTTNAME = reader.GetString(); + break; + case "CapitalCamel": + capitalCamel = reader.GetString(); + break; + case "Capital_Snake": + capitalSnake = reader.GetString(); + break; + case "SCA_ETH_Flow_Points": + sCAETHFlowPoints = reader.GetString(); + break; + case "smallCamel": + smallCamel = reader.GetString(); + break; + case "small_Snake": + smallSnake = reader.GetString(); + break; + default: + break; + } + } + } + + return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + 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); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs index b18b39a2c74..a243c2d20bd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,16 +28,17 @@ namespace Org.OpenAPITools.Model /// /// Cat /// - public partial class Cat : Animal, IEquatable + public partial class Cat : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - /// className (required) + /// className /// color (default to "red") - public Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string? color = "red") : base(className, color) + [JsonConstructor] + internal Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string color = "red") : base(className, color) { Dictionary = dictionary; CatAllOf = catAllOf; @@ -66,40 +66,6 @@ namespace Org.OpenAPITools.Model 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 Cat).AreEqual; - } - - /// - /// Returns true if Cat instances are equal - /// - /// Instance of Cat to be compared - /// Boolean - public bool Equals(Cat? 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -107,13 +73,6 @@ namespace Org.OpenAPITools.Model /// public class CatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Cat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -126,24 +85,29 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader dictionaryReader = reader; - bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref dictionaryReader, options, out Dictionary? dictionary); + bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref reader, options, out Dictionary? dictionary); Utf8JsonReader catAllOfReader = reader; - bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref catAllOfReader, options, out CatAllOf? catAllOf); + bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out CatAllOf? catAllOf); - string? className = default; - string? color = default; + string className = default; + string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -156,6 +120,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -170,6 +136,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", cat.ClassName); + writer.WriteString("color", cat.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/CatAllOf.cs index c397e1b6bc3..d3e15dd47ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// CatAllOf /// - public partial class CatAllOf : IEquatable, IValidatableObject + public partial class CatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// declawed - public CatAllOf(bool? declawed = default) + [JsonConstructor] + public CatAllOf(bool declawed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (declawed == null) + throw new ArgumentNullException("declawed is a required property for CatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Declawed = declawed; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Declawed /// [JsonPropertyName("declawed")] - public bool? Declawed { get; set; } + public bool Declawed { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,45 +74,6 @@ namespace Org.OpenAPITools.Model 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 CatAllOf).AreEqual; - } - - /// - /// Returns true if CatAllOf instances are equal - /// - /// Instance of CatAllOf to be compared - /// Boolean - public bool Equals(CatAllOf? 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) + this.Declawed.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type CatAllOf + /// + public class CatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override CatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool declawed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "declawed": + declawed = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new CatAllOf(declawed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CatAllOf catAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("declawed", catAllOf.Declawed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs index 05300f8a0b7..3de3554f727 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,39 +28,49 @@ namespace Org.OpenAPITools.Model /// /// Category /// - public partial class Category : IEquatable, IValidatableObject + public partial class Category : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) (default to "default-name") /// id - public Category(string name = "default-name", long? id = default) + /// name (default to "default-name") + [JsonConstructor] + public Category(long id, string name = "default-name") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Category and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Category and cannot be null."); - Name = name; +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; + Name = name; } + /// + /// 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 Id - /// - [JsonPropertyName("id")] - public long? Id { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -71,55 +80,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); - sb.Append(" Name: ").Append(Name).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Category).AreEqual; - } - - /// - /// Returns true if Category instances are equal - /// - /// Instance of Category to be compared - /// Boolean - public bool Equals(Category? 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -131,4 +97,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Category + /// + public class CategoryJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Category Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Category(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Category category, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)category.Id); + writer.WriteString("name", category.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs index 57c72e45da9..c10c0f93a0d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// ChildCat /// - public partial class ChildCat : ParentPet, IEquatable + public partial class ChildCat : ParentPet, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// petType (required) - public ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) + /// petType + [JsonConstructor] + internal ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) { ChildCatAllOf = childCatAllOf; } @@ -58,40 +58,6 @@ namespace Org.OpenAPITools.Model 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 ChildCat).AreEqual; - } - - /// - /// Returns true if ChildCat instances are equal - /// - /// Instance of ChildCat to be compared - /// Boolean - public bool Equals(ChildCat? 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -99,13 +65,6 @@ namespace Org.OpenAPITools.Model /// public class ChildCatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ChildCat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -118,20 +77,25 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); - Utf8JsonReader childCatAllOfReader = reader; - bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref childCatAllOfReader, options, out ChildCatAllOf? childCatAllOf); + JsonTokenType startingTokenType = reader.TokenType; - string? petType = default; + Utf8JsonReader childCatAllOfReader = reader; + bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ChildCatAllOf? childCatAllOf); + + string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -141,6 +105,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -155,6 +121,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", childCat.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index 194c0fc96ef..b1f7cbed439 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// ChildCatAllOf /// - public partial class ChildCatAllOf : IEquatable, IValidatableObject + public partial class ChildCatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name /// petType (default to PetTypeEnum.ChildCat) - public ChildCatAllOf(string? name = default, PetTypeEnum? petType = PetTypeEnum.ChildCat) + [JsonConstructor] + public ChildCatAllOf(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for ChildCatAllOf and cannot be null."); + + if (petType == null) + throw new ArgumentNullException("petType is a required property for ChildCatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; PetType = petType; } @@ -50,28 +62,54 @@ namespace Org.OpenAPITools.Model /// /// Enum ChildCat for value: ChildCat /// - [EnumMember(Value = "ChildCat")] ChildCat = 1 } + /// + /// Returns a PetTypeEnum + /// + /// + /// + public static PetTypeEnum PetTypeEnumFromString(string value) + { + if (value == "ChildCat") + return PetTypeEnum.ChildCat; + + throw new NotImplementedException($"Could not convert value to type PetTypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 PetTypeEnum? PetType { get; set; } + public PetTypeEnum PetType { get; set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string? Name { get; set; } + public string Name { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -87,49 +125,6 @@ namespace Org.OpenAPITools.Model 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 ChildCatAllOf).AreEqual; - } - - /// - /// Returns true if ChildCatAllOf instances are equal - /// - /// Instance of ChildCatAllOf to be compared - /// Boolean - public bool Equals(ChildCatAllOf? 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,4 +136,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ChildCatAllOf + /// + public class ChildCatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ChildCatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + ChildCatAllOf.PetTypeEnum petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + case "pet_type": + string petTypeRawValue = reader.GetString(); + petType = ChildCatAllOf.PetTypeEnumFromString(petTypeRawValue); + break; + default: + break; + } + } + } + + return new ChildCatAllOf(name, petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChildCatAllOf childCatAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", childCatAllOf.Name); + var petTypeRawValue = ChildCatAllOf.PetTypeEnumToJsonValue(childCatAllOf.PetType); + if (petTypeRawValue != null) + writer.WriteString("pet_type", petTypeRawValue); + else + writer.WriteNull("pet_type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs index 5e9b01f14a3..1c5262054dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,28 +28,38 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model with \"_class\" property /// - public partial class ClassModel : IEquatable, IValidatableObject + public partial class ClassModel : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _class - public ClassModel(string? _class = default) + /// classProperty + [JsonConstructor] + public ClassModel(string classProperty) { - Class = _class; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for ClassModel and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; } /// - /// Gets or Sets Class + /// Gets or Sets ClassProperty /// [JsonPropertyName("_class")] - public string? Class { get; set; } + public string ClassProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -60,53 +69,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); - sb.Append(" Class: ").Append(Class).Append("\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).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 ClassModel).AreEqual; - } - - /// - /// Returns true if ClassModel instances are equal - /// - /// Instance of ClassModel to be compared - /// Boolean - public bool Equals(ClassModel? 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; - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ClassModel + /// + public class ClassModelJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ClassModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_class": + classProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ClassModel(classProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_class", classModel.ClassProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 1a3fe55f3c5..8b964d00703 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// ComplexQuadrilateral /// - public partial class ComplexQuadrilateral : IEquatable, IValidatableObject + public partial class ComplexQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -70,44 +70,6 @@ namespace Org.OpenAPITools.Model 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 ComplexQuadrilateral).AreEqual; - } - - /// - /// Returns true if ComplexQuadrilateral instances are equal - /// - /// Instance of ComplexQuadrilateral to be compared - /// Boolean - public bool Equals(ComplexQuadrilateral? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +86,6 @@ namespace Org.OpenAPITools.Model /// public class ComplexQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ComplexQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,28 +98,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface? shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface? shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface? quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface? quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +141,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs index 9be9ffbc898..f54a10979c5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// DanishPig /// - public partial class DanishPig : IEquatable, IValidatableObject + public partial class DanishPig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public DanishPig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for DanishPig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 DanishPig).AreEqual; - } - - /// - /// Returns true if DanishPig instances are equal - /// - /// Instance of DanishPig to be compared - /// Boolean - public bool Equals(DanishPig? 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -121,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DanishPig + /// + public class DanishPigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DanishPig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new DanishPig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", danishPig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs index e5ec23562d9..7ebbabe8091 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// DeprecatedObject /// - public partial class DeprecatedObject : IEquatable, IValidatableObject + public partial class DeprecatedObject : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name - public DeprecatedObject(string? name = default) + [JsonConstructor] + public DeprecatedObject(string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for DeprecatedObject and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Name /// [JsonPropertyName("name")] - public string? Name { get; set; } + public string Name { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 DeprecatedObject).AreEqual; - } - - /// - /// Returns true if DeprecatedObject instances are equal - /// - /// Instance of DeprecatedObject to be compared - /// Boolean - public bool Equals(DeprecatedObject? 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DeprecatedObject + /// + public class DeprecatedObjectJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DeprecatedObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new DeprecatedObject(name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", deprecatedObject.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs index 7ce3f26883b..485915dd25d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,16 @@ namespace Org.OpenAPITools.Model /// /// Dog /// - public partial class Dog : Animal, IEquatable + public partial class Dog : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// className (required) + /// className /// color (default to "red") - public Dog(DogAllOf dogAllOf, string className, string? color = "red") : base(className, color) + [JsonConstructor] + internal Dog(DogAllOf dogAllOf, string className, string color = "red") : base(className, color) { DogAllOf = dogAllOf; } @@ -59,40 +59,6 @@ namespace Org.OpenAPITools.Model 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 Dog).AreEqual; - } - - /// - /// Returns true if Dog instances are equal - /// - /// Instance of Dog to be compared - /// Boolean - public bool Equals(Dog? 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -100,13 +66,6 @@ namespace Org.OpenAPITools.Model /// public class DogJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Dog).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -119,21 +78,26 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); - Utf8JsonReader dogAllOfReader = reader; - bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref dogAllOfReader, options, out DogAllOf? dogAllOf); + JsonTokenType startingTokenType = reader.TokenType; - string? className = default; - string? color = default; + Utf8JsonReader dogAllOfReader = reader; + bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out DogAllOf? dogAllOf); + + string className = default; + string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -146,6 +110,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -160,6 +126,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", dog.ClassName); + writer.WriteString("color", dog.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DogAllOf.cs index f6a94b443ea..06248bb34ff 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// DogAllOf /// - public partial class DogAllOf : IEquatable, IValidatableObject + public partial class DogAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// breed - public DogAllOf(string? breed = default) + [JsonConstructor] + public DogAllOf(string breed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (breed == null) + throw new ArgumentNullException("breed is a required property for DogAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Breed = breed; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Breed /// [JsonPropertyName("breed")] - public string? Breed { get; set; } + public string Breed { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 DogAllOf).AreEqual; - } - - /// - /// Returns true if DogAllOf instances are equal - /// - /// Instance of DogAllOf to be compared - /// Boolean - public bool Equals(DogAllOf? 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; - if (this.Breed != null) - { - hashCode = (hashCode * 59) + this.Breed.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DogAllOf + /// + public class DogAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DogAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string breed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "breed": + breed = reader.GetString(); + break; + default: + break; + } + } + } + + return new DogAllOf(breed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DogAllOf dogAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("breed", dogAllOf.Breed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs index b5d4b43be10..72a19246c84 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,34 +28,56 @@ namespace Org.OpenAPITools.Model /// /// Drawing /// - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape /// shapeOrNull - /// nullableShape /// shapes - public Drawing(Shape? mainShape = default, ShapeOrNull? shapeOrNull = default, NullableShape? nullableShape = default, List? shapes = default) : base() + /// nullableShape + [JsonConstructor] + public Drawing(Shape mainShape, ShapeOrNull shapeOrNull, List shapes, NullableShape? nullableShape = default) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mainShape == null) + throw new ArgumentNullException("mainShape is a required property for Drawing and cannot be null."); + + if (shapeOrNull == null) + throw new ArgumentNullException("shapeOrNull is a required property for Drawing and cannot be null."); + + if (shapes == null) + throw new ArgumentNullException("shapes is a required property for Drawing and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + MainShape = mainShape; ShapeOrNull = shapeOrNull; - NullableShape = nullableShape; Shapes = shapes; + NullableShape = nullableShape; } /// /// Gets or Sets MainShape /// [JsonPropertyName("mainShape")] - public Shape? MainShape { get; set; } + public Shape MainShape { get; set; } /// /// Gets or Sets ShapeOrNull /// [JsonPropertyName("shapeOrNull")] - public ShapeOrNull? ShapeOrNull { get; set; } + public ShapeOrNull ShapeOrNull { get; set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List Shapes { get; set; } /// /// Gets or Sets NullableShape @@ -64,12 +85,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("nullableShape")] public NullableShape? NullableShape { get; set; } - /// - /// Gets or Sets Shapes - /// - [JsonPropertyName("shapes")] - public List? Shapes { get; set; } - /// /// Returns the string presentation of the object /// @@ -81,61 +96,11 @@ namespace Org.OpenAPITools.Model sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); - sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" NullableShape: ").Append(NullableShape).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 Drawing).AreEqual; - } - - /// - /// Returns true if Drawing instances are equal - /// - /// Instance of Drawing to be compared - /// Boolean - public bool Equals(Drawing? 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 = base.GetHashCode(); - if (this.MainShape != null) - { - hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); - } - if (this.ShapeOrNull != null) - { - hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); - } - if (this.NullableShape != null) - { - hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); - } - if (this.Shapes != null) - { - hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -147,4 +112,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Drawing + /// + public class DrawingJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Drawing Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Shape mainShape = default; + ShapeOrNull shapeOrNull = default; + List shapes = default; + NullableShape nullableShape = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "mainShape": + mainShape = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapeOrNull": + shapeOrNull = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapes": + shapes = JsonSerializer.Deserialize>(ref reader, options); + break; + case "nullableShape": + nullableShape = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new Drawing(mainShape, shapeOrNull, shapes, nullableShape); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, options); + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, options); + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, options); + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs index 951d98e6626..8040834df48 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,80 @@ namespace Org.OpenAPITools.Model /// /// EnumArrays /// - public partial class EnumArrays : IEquatable, IValidatableObject + public partial class EnumArrays : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum? justSymbol = default, List? arrayEnum = default) + /// justSymbol + [JsonConstructor] + public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) { - JustSymbol = justSymbol; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justSymbol == null) + throw new ArgumentNullException("justSymbol is a required property for EnumArrays and cannot be null."); + + if (arrayEnum == null) + throw new ArgumentNullException("arrayEnum is a required property for EnumArrays and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayEnum = arrayEnum; + JustSymbol = justSymbol; + } + + /// + /// Defines ArrayEnum + /// + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + Crab = 2 + + } + + /// + /// Returns a ArrayEnumEnum + /// + /// + /// + public static ArrayEnumEnum ArrayEnumEnumFromString(string value) + { + if (value == "fish") + return ArrayEnumEnum.Fish; + + if (value == "crab") + return ArrayEnumEnum.Crab; + + throw new NotImplementedException($"Could not convert value to type ArrayEnumEnum: '{value}'"); + } + + /// + /// Returns equivalent 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}'"); } /// @@ -50,53 +112,65 @@ namespace Org.OpenAPITools.Model /// /// Enum GreaterThanOrEqualTo for value: >= /// - [EnumMember(Value = ">=")] GreaterThanOrEqualTo = 1, /// /// Enum Dollar for value: $ /// - [EnumMember(Value = "$")] Dollar = 2 } + /// + /// Returns a JustSymbolEnum + /// + /// + /// + public static JustSymbolEnum JustSymbolEnumFromString(string value) + { + if (value == ">=") + return JustSymbolEnum.GreaterThanOrEqualTo; + + if (value == "$") + return JustSymbolEnum.Dollar; + + throw new NotImplementedException($"Could not convert value to type JustSymbolEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } - - /// - /// Defines ArrayEnum - /// - public enum ArrayEnumEnum - { - /// - /// Enum Fish for value: fish - /// - [EnumMember(Value = "fish")] - Fish = 1, - - /// - /// Enum Crab for value: crab - /// - [EnumMember(Value = "crab")] - Crab = 2 - - } + public JustSymbolEnum JustSymbol { get; set; } /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List? ArrayEnum { get; set; } + public List ArrayEnum { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -106,55 +180,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); - sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumArrays).AreEqual; - } - - /// - /// Returns true if EnumArrays instances are equal - /// - /// Instance of EnumArrays to be compared - /// Boolean - public bool Equals(EnumArrays? 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) + this.JustSymbol.GetHashCode(); - if (this.ArrayEnum != null) - { - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -166,4 +197,82 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumArrays + /// + public class EnumArraysJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumArrays Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayEnum = default; + EnumArrays.JustSymbolEnum justSymbol = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_enum": + arrayEnum = JsonSerializer.Deserialize>(ref reader, options); + break; + case "just_symbol": + string justSymbolRawValue = reader.GetString(); + justSymbol = EnumArrays.JustSymbolEnumFromString(justSymbolRawValue); + break; + default: + break; + } + } + } + + return new EnumArrays(arrayEnum, justSymbol); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, options); + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); + if (justSymbolRawValue != null) + writer.WriteString("just_symbol", justSymbolRawValue); + else + writer.WriteNull("just_symbol"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs index 9aa3badce21..5aa241352e5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,20 +33,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Abc for value: _abc /// - [EnumMember(Value = "_abc")] Abc = 1, /// /// Enum Efg for value: -efg /// - [EnumMember(Value = "-efg")] Efg = 2, /// /// Enum Xyz for value: (xyz) /// - [EnumMember(Value = "(xyz)")] Xyz = 3 } + + public class EnumClassConverter : JsonConverter + { + public static EnumClass FromString(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + throw new NotImplementedException($"Could not convert value to type EnumClass: '{value}'"); + } + + public static EnumClass? FromStringOrDefault(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override EnumClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + EnumClass? result = EnumClassConverter.FromString(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()); + } + } + + public class EnumClassNullableConverter : JsonConverter + { + /// + /// Returns a EnumClass from the Json object + /// + /// + /// + /// + /// + public override EnumClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + EnumClass? result = EnumClassConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs index c8f0a683357..9b9889a0204 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,98 +28,64 @@ namespace Org.OpenAPITools.Model /// /// EnumTest /// - public partial class EnumTest : IEquatable, IValidatableObject + public partial class EnumTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// enumStringRequired (required) - /// enumString /// enumInteger /// enumIntegerOnly /// enumNumber - /// outerEnum - /// outerEnumInteger + /// enumString + /// enumStringRequired /// outerEnumDefaultValue + /// outerEnumInteger /// outerEnumIntegerDefaultValue - public EnumTest(EnumStringRequiredEnum enumStringRequired, EnumStringEnum? enumString = default, EnumIntegerEnum? enumInteger = default, EnumIntegerOnlyEnum? enumIntegerOnly = default, EnumNumberEnum? enumNumber = default, OuterEnum? outerEnum = default, OuterEnumInteger? outerEnumInteger = default, OuterEnumDefaultValue? outerEnumDefaultValue = default, OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default) + /// outerEnum + [JsonConstructor] + public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (enumString == null) + throw new ArgumentNullException("enumString is a required property for EnumTest and cannot be null."); + if (enumStringRequired == null) throw new ArgumentNullException("enumStringRequired is a required property for EnumTest and cannot be null."); - EnumStringRequired = enumStringRequired; - EnumString = enumString; + if (enumInteger == null) + throw new ArgumentNullException("enumInteger is a required property for EnumTest and cannot be null."); + + if (enumIntegerOnly == null) + throw new ArgumentNullException("enumIntegerOnly is a required property for EnumTest and cannot be null."); + + if (enumNumber == null) + throw new ArgumentNullException("enumNumber is a required property for EnumTest and cannot be null."); + + if (outerEnumInteger == null) + throw new ArgumentNullException("outerEnumInteger is a required property for EnumTest and cannot be null."); + + if (outerEnumDefaultValue == null) + throw new ArgumentNullException("outerEnumDefaultValue is a required property for EnumTest and cannot be null."); + + if (outerEnumIntegerDefaultValue == null) + throw new ArgumentNullException("outerEnumIntegerDefaultValue is a required property for EnumTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + EnumInteger = enumInteger; EnumIntegerOnly = enumIntegerOnly; EnumNumber = enumNumber; - OuterEnum = outerEnum; - OuterEnumInteger = outerEnumInteger; + EnumString = enumString; + EnumStringRequired = enumStringRequired; OuterEnumDefaultValue = outerEnumDefaultValue; + OuterEnumInteger = outerEnumInteger; OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + OuterEnum = outerEnum; } - /// - /// Defines EnumStringRequired - /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumStringRequired - /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } - - /// - /// Defines EnumString - /// - public enum EnumStringEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumString - /// - [JsonPropertyName("enum_string")] - public EnumStringEnum? EnumString { get; set; } - /// /// Defines EnumInteger /// @@ -138,11 +103,38 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerEnum + /// + /// + /// + public static EnumIntegerEnum EnumIntegerEnumFromString(string value) + { + if (value == (1).ToString()) + return EnumIntegerEnum.NUMBER_1; + + if (value == (-1).ToString()) + return EnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumInteger /// [JsonPropertyName("enum_integer")] - public EnumIntegerEnum? EnumInteger { get; set; } + public EnumIntegerEnum EnumInteger { get; set; } /// /// Defines EnumIntegerOnly @@ -161,11 +153,38 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerOnlyEnum + /// + /// + /// + public static EnumIntegerOnlyEnum EnumIntegerOnlyEnumFromString(string value) + { + if (value == (2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_2; + + if (value == (-2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumIntegerOnly /// [JsonPropertyName("enum_integer_only")] - public EnumIntegerOnlyEnum? EnumIntegerOnly { get; set; } + public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } /// /// Defines EnumNumber @@ -175,22 +194,205 @@ namespace Org.OpenAPITools.Model /// /// Enum NUMBER_1_DOT_1 for value: 1.1 /// - [EnumMember(Value = "1.1")] NUMBER_1_DOT_1 = 1, /// /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 /// - [EnumMember(Value = "-1.2")] NUMBER_MINUS_1_DOT_2 = 2 } + /// + /// Returns a EnumNumberEnum + /// + /// + /// + public static EnumNumberEnum EnumNumberEnumFromString(string value) + { + if (value == "1.1") + return EnumNumberEnum.NUMBER_1_DOT_1; + + if (value == "-1.2") + return EnumNumberEnum.NUMBER_MINUS_1_DOT_2; + + throw new NotImplementedException($"Could not convert value to type EnumNumberEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static string 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; } + 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 + + } + + /// + /// Returns a EnumStringEnum + /// + /// + /// + public static EnumStringEnum EnumStringEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringEnum.UPPER; + + if (value == "lower") + return EnumStringEnum.Lower; + + if (value == "") + return EnumStringEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 + + } + + /// + /// Returns a EnumStringRequiredEnum + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringRequiredEnum.UPPER; + + if (value == "lower") + return EnumStringRequiredEnum.Lower; + + if (value == "") + return EnumStringRequiredEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 @@ -198,29 +400,11 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("outerEnum")] public OuterEnum? OuterEnum { get; set; } - /// - /// Gets or Sets OuterEnumInteger - /// - [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger? OuterEnumInteger { get; set; } - - /// - /// Gets or Sets OuterEnumDefaultValue - /// - [JsonPropertyName("outerEnumDefaultValue")] - public OuterEnumDefaultValue? OuterEnumDefaultValue { get; set; } - - /// - /// Gets or Sets OuterEnumIntegerDefaultValue - /// - [JsonPropertyName("outerEnumIntegerDefaultValue")] - public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -230,66 +414,19 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); - sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); - sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumTest).AreEqual; - } - - /// - /// Returns true if EnumTest instances are equal - /// - /// Instance of EnumTest to be compared - /// Boolean - public bool Equals(EnumTest? 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) + this.EnumStringRequired.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -301,4 +438,143 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumTest + /// + public class EnumTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "enum_integer": + enumInteger = (EnumTest.EnumIntegerEnum) reader.GetInt32(); + break; + case "enum_integer_only": + enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum) reader.GetInt32(); + break; + case "enum_number": + enumNumber = (EnumTest.EnumNumberEnum) reader.GetInt32(); + break; + case "enum_string": + string enumStringRawValue = reader.GetString(); + enumString = EnumTest.EnumStringEnumFromString(enumStringRawValue); + break; + case "enum_string_required": + string enumStringRequiredRawValue = reader.GetString(); + enumStringRequired = EnumTest.EnumStringRequiredEnumFromString(enumStringRequiredRawValue); + break; + case "outerEnumDefaultValue": + string outerEnumDefaultValueRawValue = reader.GetString(); + outerEnumDefaultValue = OuterEnumDefaultValueConverter.FromString(outerEnumDefaultValueRawValue); + break; + case "outerEnumInteger": + string outerEnumIntegerRawValue = reader.GetString(); + outerEnumInteger = OuterEnumIntegerConverter.FromString(outerEnumIntegerRawValue); + break; + case "outerEnumIntegerDefaultValue": + string outerEnumIntegerDefaultValueRawValue = reader.GetString(); + outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValueConverter.FromString(outerEnumIntegerDefaultValueRawValue); + break; + case "outerEnum": + string outerEnumRawValue = reader.GetString(); + outerEnum = OuterEnumConverter.FromStringOrDefault(outerEnumRawValue); + break; + default: + break; + } + } + } + + return new EnumTest(enumInteger, enumIntegerOnly, enumNumber, enumString, enumStringRequired, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue, outerEnum); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("enum_integer", (int)enumTest.EnumInteger); + writer.WriteNumber("enum_integer_only", (int)enumTest.EnumIntegerOnly); + writer.WriteNumber("enum_number", (int)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 = OuterEnumDefaultValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (outerEnumDefaultValueRawValue != null) + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + else + writer.WriteNull("outerEnumDefaultValue"); + var outerEnumIntegerRawValue = OuterEnumIntegerConverter.ToJsonValue(enumTest.OuterEnumInteger); + if (outerEnumIntegerRawValue != null) + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + else + writer.WriteNull("outerEnumInteger"); + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); + if (outerEnumIntegerDefaultValueRawValue != null) + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + else + writer.WriteNull("outerEnumIntegerDefaultValue"); + if (enumTest.OuterEnum == null) + writer.WriteNull("outerEnum"); + var outerEnumRawValue = OuterEnumConverter.ToJsonValue(enumTest.OuterEnum.Value); + if (outerEnumRawValue != null) + writer.WriteString("outerEnum", outerEnumRawValue); + else + writer.WriteNull("outerEnum"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 8a4946d99b8..61a3ce92097 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// EquilateralTriangle /// - public partial class EquilateralTriangle : IEquatable, IValidatableObject + public partial class EquilateralTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -70,44 +70,6 @@ namespace Org.OpenAPITools.Model 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 EquilateralTriangle).AreEqual; - } - - /// - /// Returns true if EquilateralTriangle instances are equal - /// - /// Instance of EquilateralTriangle to be compared - /// Boolean - public bool Equals(EquilateralTriangle? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +86,6 @@ namespace Org.OpenAPITools.Model /// public class EquilateralTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(EquilateralTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,28 +98,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface? shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface? shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface? triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface? triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +141,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs index 2ae90b249a2..34867c689e3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// Must be named `File` for test. /// - public partial class File : IEquatable, IValidatableObject + public partial class File : IValidatableObject { /// /// Initializes a new instance of the class. /// /// Test capitalization - public File(string? sourceURI = default) + [JsonConstructor] + public File(string sourceURI) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (sourceURI == null) + throw new ArgumentNullException("sourceURI is a required property for File and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + SourceURI = sourceURI; } @@ -45,13 +54,13 @@ namespace Org.OpenAPITools.Model /// /// Test capitalization [JsonPropertyName("sourceURI")] - public string? SourceURI { get; set; } + public string SourceURI { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +75,6 @@ namespace Org.OpenAPITools.Model 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 File).AreEqual; - } - - /// - /// Returns true if File instances are equal - /// - /// Instance of File to be compared - /// Boolean - public bool Equals(File? 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; - if (this.SourceURI != null) - { - hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +86,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type File + /// + public class FileJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override File Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string sourceURI = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "sourceURI": + sourceURI = reader.GetString(); + break; + default: + break; + } + } + } + + return new File(sourceURI); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("sourceURI", file.SourceURI); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 26c1e83b07a..209344ad13a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// FileSchemaTestClass /// - public partial class FileSchemaTestClass : IEquatable, IValidatableObject + public partial class FileSchemaTestClass : IValidatableObject { /// /// Initializes a new instance of the class. /// /// file /// files - public FileSchemaTestClass(File? file = default, List? files = default) + [JsonConstructor] + public FileSchemaTestClass(File file, List files) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (file == null) + throw new ArgumentNullException("file is a required property for FileSchemaTestClass and cannot be null."); + + if (files == null) + throw new ArgumentNullException("files is a required property for FileSchemaTestClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + File = file; Files = files; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets File /// [JsonPropertyName("file")] - public File? File { get; set; } + public File File { get; set; } /// /// Gets or Sets Files /// [JsonPropertyName("files")] - public List? Files { get; set; } + public List Files { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,52 +86,6 @@ namespace Org.OpenAPITools.Model 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 FileSchemaTestClass).AreEqual; - } - - /// - /// Returns true if FileSchemaTestClass instances are equal - /// - /// Instance of FileSchemaTestClass to be compared - /// Boolean - public bool Equals(FileSchemaTestClass? 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; - if (this.File != null) - { - hashCode = (hashCode * 59) + this.File.GetHashCode(); - } - if (this.Files != null) - { - hashCode = (hashCode * 59) + this.Files.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -131,4 +97,78 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FileSchemaTestClass + /// + public class FileSchemaTestClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FileSchemaTestClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + File file = default; + List files = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "file": + file = JsonSerializer.Deserialize(ref reader, options); + break; + case "files": + files = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new FileSchemaTestClass(file, files); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, options); + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs index 4997e8d3bb7..5cc4464b054 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// Foo /// - public partial class Foo : IEquatable, IValidatableObject + public partial class Foo : IValidatableObject { /// /// Initializes a new instance of the class. /// /// bar (default to "bar") - public Foo(string? bar = "bar") + [JsonConstructor] + public Foo(string bar = "bar") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for Foo and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string? Bar { get; set; } + public string Bar { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 Foo).AreEqual; - } - - /// - /// Returns true if Foo instances are equal - /// - /// Instance of Foo to be compared - /// Boolean - public bool Equals(Foo? 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; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Foo + /// + public class FooJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Foo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + default: + break; + } + } + } + + return new Foo(bar); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", foo.Bar); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index 5cd966c64a6..a78484e9493 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,28 +28,38 @@ namespace Org.OpenAPITools.Model /// /// FooGetDefaultResponse /// - public partial class FooGetDefaultResponse : IEquatable, IValidatableObject + public partial class FooGetDefaultResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _string - public FooGetDefaultResponse(Foo? _string = default) + /// stringProperty + [JsonConstructor] + public FooGetDefaultResponse(Foo stringProperty) { - String = _string; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FooGetDefaultResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + StringProperty = stringProperty; } /// - /// Gets or Sets String + /// Gets or Sets StringProperty /// [JsonPropertyName("string")] - public Foo? String { get; set; } + public Foo StringProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -60,53 +69,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FooGetDefaultResponse {\n"); - sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).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 FooGetDefaultResponse).AreEqual; - } - - /// - /// Returns true if FooGetDefaultResponse instances are equal - /// - /// Instance of FooGetDefaultResponse to be compared - /// Boolean - public bool Equals(FooGetDefaultResponse? 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; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FooGetDefaultResponse + /// + public class FooGetDefaultResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FooGetDefaultResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Foo stringProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "string": + stringProperty = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new FooGetDefaultResponse(stringProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.StringProperty, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs index e3fc4c55e83..4c4cf76e23a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,70 +28,113 @@ namespace Org.OpenAPITools.Model /// /// FormatTest /// - public partial class FormatTest : IEquatable, IValidatableObject + public partial class FormatTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// number (required) - /// _byte (required) - /// date (required) - /// password (required) - /// integer + /// binary + /// byteProperty + /// date + /// dateTime + /// decimalProperty + /// doubleProperty + /// floatProperty /// int32 /// int64 - /// _float - /// _double - /// _decimal - /// _string - /// binary - /// dateTime - /// uuid + /// integer + /// number + /// password /// 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. - public FormatTest(decimal number, byte[] _byte, DateTime date, string password, int? integer = default, int? int32 = default, long? int64 = default, float? _float = default, double? _double = default, decimal? _decimal = default, string? _string = default, System.IO.Stream? binary = default, DateTime? dateTime = default, Guid? uuid = default, string? patternWithDigits = default, string? patternWithDigitsAndDelimiter = default) + /// stringProperty + /// uuid + [JsonConstructor] + public FormatTest(System.IO.Stream binary, byte[] byteProperty, DateTime date, DateTime dateTime, decimal decimalProperty, double doubleProperty, float floatProperty, int int32, long int64, int integer, decimal number, string password, string patternWithDigits, string patternWithDigitsAndDelimiter, string stringProperty, Guid uuid) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (integer == null) + throw new ArgumentNullException("integer is a required property for FormatTest and cannot be null."); + + if (int32 == null) + throw new ArgumentNullException("int32 is a required property for FormatTest and cannot be null."); + + if (int64 == null) + throw new ArgumentNullException("int64 is a required property for FormatTest and cannot be null."); + if (number == null) throw new ArgumentNullException("number is a required property for FormatTest and cannot be null."); - if (_byte == null) - throw new ArgumentNullException("_byte is a required property for FormatTest and cannot be null."); + if (floatProperty == null) + throw new ArgumentNullException("floatProperty is a required property for FormatTest and cannot be null."); + + if (doubleProperty == null) + throw new ArgumentNullException("doubleProperty is a required property for FormatTest and cannot be null."); + + if (decimalProperty == null) + throw new ArgumentNullException("decimalProperty is a required property for FormatTest and cannot be null."); + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FormatTest and cannot be null."); + + if (byteProperty == null) + throw new ArgumentNullException("byteProperty is a required property for FormatTest and cannot be null."); + + if (binary == null) + throw new ArgumentNullException("binary is a required property for FormatTest and cannot be null."); if (date == null) throw new ArgumentNullException("date is a required property for FormatTest and cannot be null."); + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for FormatTest and cannot be null."); + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for FormatTest and cannot be null."); + if (password == null) throw new ArgumentNullException("password is a required property for FormatTest and cannot be null."); - Number = number; - Byte = _byte; + if (patternWithDigits == null) + throw new ArgumentNullException("patternWithDigits is a required property for FormatTest and cannot be null."); + + if (patternWithDigitsAndDelimiter == null) + throw new ArgumentNullException("patternWithDigitsAndDelimiter is a required property for FormatTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Binary = binary; + ByteProperty = byteProperty; Date = date; - Password = password; - Integer = integer; + DateTime = dateTime; + DecimalProperty = decimalProperty; + DoubleProperty = doubleProperty; + FloatProperty = floatProperty; Int32 = int32; Int64 = int64; - Float = _float; - Double = _double; - Decimal = _decimal; - String = _string; - Binary = binary; - DateTime = dateTime; - Uuid = uuid; + Integer = integer; + Number = number; + Password = password; PatternWithDigits = patternWithDigits; PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + StringProperty = stringProperty; + Uuid = uuid; } /// - /// Gets or Sets Number + /// Gets or Sets Binary /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get; set; } /// - /// Gets or Sets Byte + /// Gets or Sets ByteProperty /// [JsonPropertyName("byte")] - public byte[] Byte { get; set; } + public byte[] ByteProperty { get; set; } /// /// Gets or Sets Date @@ -100,91 +142,91 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("date")] public DateTime Date { get; set; } + /// + /// Gets or Sets DateTime + /// + [JsonPropertyName("dateTime")] + public DateTime DateTime { get; set; } + + /// + /// Gets or Sets DecimalProperty + /// + [JsonPropertyName("decimal")] + public decimal DecimalProperty { get; set; } + + /// + /// Gets or Sets DoubleProperty + /// + [JsonPropertyName("double")] + public double DoubleProperty { get; set; } + + /// + /// Gets or Sets FloatProperty + /// + [JsonPropertyName("float")] + public float FloatProperty { 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; } - /// - /// Gets or Sets Integer - /// - [JsonPropertyName("integer")] - public int? Integer { 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 Float - /// - [JsonPropertyName("float")] - public float? Float { get; set; } - - /// - /// Gets or Sets Double - /// - [JsonPropertyName("double")] - public double? Double { get; set; } - - /// - /// Gets or Sets Decimal - /// - [JsonPropertyName("decimal")] - public decimal? Decimal { get; set; } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public string? String { get; set; } - - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream? Binary { get; set; } - - /// - /// Gets or Sets DateTime - /// - [JsonPropertyName("dateTime")] - public DateTime? DateTime { get; set; } - - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid? Uuid { 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; } + 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; } + public string PatternWithDigitsAndDelimiter { get; set; } + + /// + /// Gets or Sets StringProperty + /// + [JsonPropertyName("string")] + public string StringProperty { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -194,107 +236,26 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" ByteProperty: ").Append(ByteProperty).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" DecimalProperty: ").Append(DecimalProperty).Append("\n"); + sb.Append(" DoubleProperty: ").Append(DoubleProperty).Append("\n"); + sb.Append(" FloatProperty: ").Append(FloatProperty).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" Decimal: ").Append(Decimal).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Uuid: ").Append(Uuid).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(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 FormatTest).AreEqual; - } - - /// - /// Returns true if FormatTest instances are equal - /// - /// Instance of FormatTest to be compared - /// Boolean - public bool Equals(FormatTest? 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) + this.Number.GetHashCode(); - if (this.Byte != null) - { - hashCode = (hashCode * 59) + this.Byte.GetHashCode(); - } - if (this.Date != null) - { - hashCode = (hashCode * 59) + this.Date.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Integer.GetHashCode(); - hashCode = (hashCode * 59) + this.Int32.GetHashCode(); - hashCode = (hashCode * 59) + this.Int64.GetHashCode(); - hashCode = (hashCode * 59) + this.Float.GetHashCode(); - hashCode = (hashCode * 59) + this.Double.GetHashCode(); - hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.Binary != null) - { - hashCode = (hashCode * 59) + this.Binary.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.PatternWithDigits != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); - } - if (this.PatternWithDigitsAndDelimiter != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -302,6 +263,54 @@ namespace Org.OpenAPITools.Model /// Validation Result public IEnumerable Validate(ValidationContext validationContext) { + // DoubleProperty (double) maximum + if (this.DoubleProperty > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value less than or equal to 123.4.", new [] { "DoubleProperty" }); + } + + // DoubleProperty (double) minimum + if (this.DoubleProperty < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value greater than or equal to 67.8.", new [] { "DoubleProperty" }); + } + + // FloatProperty (float) maximum + if (this.FloatProperty > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value less than or equal to 987.6.", new [] { "FloatProperty" }); + } + + // FloatProperty (float) minimum + if (this.FloatProperty < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value greater than or equal to 54.3.", new [] { "FloatProperty" }); + } + + // 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) { @@ -326,61 +335,6 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } - // 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" }); - } - - // 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" }); - } - - // Float (float) maximum - if (this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Float (float) minimum - if (this.Float < (float)54.3) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); - } - - // Double (double) maximum - if (this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if (this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\\d{10}$", RegexOptions.CultureInvariant); if (false == regexPatternWithDigits.Match(this.PatternWithDigits).Success) @@ -395,8 +349,162 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } + // StringProperty (string) pattern + Regex regexStringProperty = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexStringProperty.Match(this.StringProperty).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StringProperty, must match a pattern of " + regexStringProperty, new [] { "StringProperty" }); + } + yield break; } } + /// + /// A Json converter for type FormatTest + /// + public class FormatTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FormatTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + System.IO.Stream binary = default; + byte[] byteProperty = default; + DateTime date = default; + DateTime dateTime = default; + decimal decimalProperty = default; + double doubleProperty = default; + float floatProperty = default; + int int32 = default; + long int64 = default; + int integer = default; + decimal number = default; + string password = default; + string patternWithDigits = default; + string patternWithDigitsAndDelimiter = default; + string stringProperty = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "binary": + binary = JsonSerializer.Deserialize(ref reader, options); + break; + case "byte": + byteProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "date": + date = JsonSerializer.Deserialize(ref reader, options); + break; + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "decimal": + decimalProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "double": + doubleProperty = reader.GetDouble(); + break; + case "float": + floatProperty = (float)reader.GetDouble(); + break; + case "int32": + int32 = reader.GetInt32(); + break; + case "int64": + int64 = reader.GetInt64(); + break; + case "integer": + integer = reader.GetInt32(); + break; + case "number": + number = reader.GetInt32(); + break; + case "password": + password = reader.GetString(); + break; + case "pattern_with_digits": + patternWithDigits = reader.GetString(); + break; + case "pattern_with_digits_and_delimiter": + patternWithDigitsAndDelimiter = reader.GetString(); + break; + case "string": + stringProperty = reader.GetString(); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new FormatTest(binary, byteProperty, date, dateTime, decimalProperty, doubleProperty, floatProperty, int32, int64, integer, number, password, patternWithDigits, patternWithDigitsAndDelimiter, stringProperty, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, options); + writer.WritePropertyName("byte"); + JsonSerializer.Serialize(writer, formatTest.ByteProperty, options); + writer.WritePropertyName("date"); + JsonSerializer.Serialize(writer, formatTest.Date, options); + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, formatTest.DateTime, options); + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.DecimalProperty, options); + writer.WriteNumber("double", (int)formatTest.DoubleProperty); + writer.WriteNumber("float", (int)formatTest.FloatProperty); + writer.WriteNumber("int32", (int)formatTest.Int32); + writer.WriteNumber("int64", (int)formatTest.Int64); + writer.WriteNumber("integer", (int)formatTest.Integer); + writer.WriteNumber("number", (int)formatTest.Number); + writer.WriteString("password", formatTest.Password); + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + writer.WriteString("string", formatTest.StringProperty); + writer.WriteString("uuid", formatTest.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs index 4e173ba6d51..e3bad64b289 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,25 @@ namespace Org.OpenAPITools.Model /// /// Fruit /// - public partial class Fruit : IEquatable, IValidatableObject + public partial class Fruit : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// color - public Fruit(Apple? apple, string? color = default) + [JsonConstructor] + public Fruit(Apple? apple, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = apple; Color = color; } @@ -47,8 +56,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public Fruit(Banana banana, string? color = default) + [JsonConstructor] + public Fruit(Banana banana, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Banana = banana; Color = color; } @@ -61,13 +80,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Banana /// - public Banana Banana { get; set; } + public Banana? Banana { get; set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string? Color { get; set; } + public string Color { get; set; } /// /// Returns the string presentation of the object @@ -81,44 +100,6 @@ namespace Org.OpenAPITools.Model 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 Fruit).AreEqual; - } - - /// - /// Returns true if Fruit instances are equal - /// - /// Instance of Fruit to be compared - /// Boolean - public bool Equals(Fruit? 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -135,13 +116,6 @@ namespace Org.OpenAPITools.Model /// public class FruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Fruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -154,23 +128,28 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple? apple); Utf8JsonReader bananaReader = reader; bool bananaDeserialized = Client.ClientUtils.TryDeserialize(ref bananaReader, options, out Banana? banana); - string? color = default; + string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -180,6 +159,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -200,6 +181,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", fruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs index 98f30ed1e7d..5086fba2184 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// FruitReq /// - public partial class FruitReq : IEquatable, IValidatableObject + public partial class FruitReq : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public FruitReq(AppleReq appleReq) + [JsonConstructor] + internal FruitReq(AppleReq appleReq) { AppleReq = appleReq; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public FruitReq(BananaReq bananaReq) + [JsonConstructor] + internal FruitReq(BananaReq bananaReq) { BananaReq = bananaReq; } @@ -52,12 +53,12 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets AppleReq /// - public AppleReq AppleReq { get; set; } + public AppleReq? AppleReq { get; set; } /// /// Gets or Sets BananaReq /// - public BananaReq BananaReq { get; set; } + public BananaReq? BananaReq { get; set; } /// /// Returns the string presentation of the object @@ -70,40 +71,6 @@ namespace Org.OpenAPITools.Model 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 FruitReq).AreEqual; - } - - /// - /// Returns true if FruitReq instances are equal - /// - /// Instance of FruitReq to be compared - /// Boolean - public bool Equals(FruitReq? 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -120,13 +87,6 @@ namespace Org.OpenAPITools.Model /// public class FruitReqJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(FruitReq).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -139,9 +99,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReqReader = reader; bool appleReqDeserialized = Client.ClientUtils.TryDeserialize(ref appleReqReader, options, out AppleReq? appleReq); @@ -151,16 +113,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -181,6 +148,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs index bdb883115d6..94525cb6c9c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,7 +28,7 @@ namespace Org.OpenAPITools.Model /// /// GmFruit /// - public partial class GmFruit : IEquatable, IValidatableObject + public partial class GmFruit : IValidatableObject { /// /// Initializes a new instance of the class. @@ -37,8 +36,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public GmFruit(Apple? apple, Banana banana, string? color = default) + [JsonConstructor] + public GmFruit(Apple? apple, Banana banana, string color) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException("color is a required property for GmFruit and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = Apple; Banana = Banana; Color = color; @@ -52,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Banana /// - public Banana Banana { get; set; } + public Banana? Banana { get; set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string? Color { get; set; } + public string Color { get; set; } /// /// Returns the string presentation of the object @@ -72,44 +81,6 @@ namespace Org.OpenAPITools.Model 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 GmFruit).AreEqual; - } - - /// - /// Returns true if GmFruit instances are equal - /// - /// Instance of GmFruit to be compared - /// Boolean - public bool Equals(GmFruit? 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,13 +97,6 @@ namespace Org.OpenAPITools.Model /// public class GmFruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(GmFruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -145,23 +109,28 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple? apple); Utf8JsonReader bananaReader = reader; bool bananaDeserialized = Client.ClientUtils.TryDeserialize(ref bananaReader, options, out Banana? banana); - string? color = default; + string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -171,6 +140,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -185,6 +156,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", gmFruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index ba90bb46872..28b104fb7cf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// GrandparentAnimal /// - public partial class GrandparentAnimal : IEquatable, IValidatableObject + public partial class GrandparentAnimal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) + /// petType + [JsonConstructor] public GrandparentAnimal(string petType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (petType == null) throw new ArgumentNullException("petType is a required property for GrandparentAnimal and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + PetType = petType; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 GrandparentAnimal).AreEqual; - } - - /// - /// Returns true if GrandparentAnimal instances are equal - /// - /// Instance of GrandparentAnimal to be compared - /// Boolean - public bool Equals(GrandparentAnimal? 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; - if (this.PetType != null) - { - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -131,4 +95,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type GrandparentAnimal + /// + public class GrandparentAnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override GrandparentAnimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "pet_type": + petType = reader.GetString(); + break; + default: + break; + } + } + } + + return new GrandparentAnimal(petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", grandparentAnimal.PetType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index ae81256f825..9e549290fe2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// HasOnlyReadOnly /// - public partial class HasOnlyReadOnly : IEquatable, IValidatableObject + public partial class HasOnlyReadOnly : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// bar /// foo - public HasOnlyReadOnly(string? bar = default, string? foo = default) + [JsonConstructor] + internal HasOnlyReadOnly(string bar, string foo) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for HasOnlyReadOnly and cannot be null."); + + if (foo == null) + throw new ArgumentNullException("foo is a required property for HasOnlyReadOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Foo = foo; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string? Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string? Foo { get; private set; } + public string Foo { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -104,22 +116,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Foo != null) - { - hashCode = (hashCode * 59) + this.Foo.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -131,4 +134,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HasOnlyReadOnly + /// + public class HasOnlyReadOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HasOnlyReadOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string foo = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "foo": + foo = reader.GetString(); + break; + default: + break; + } + } + } + + return new HasOnlyReadOnly(bar, foo); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", hasOnlyReadOnly.Bar); + writer.WriteString("foo", hasOnlyReadOnly.Foo); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 34a2909e1c3..70ea7fe99e5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,12 +28,13 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class HealthCheckResult : IValidatableObject { /// /// Initializes a new instance of the class. /// /// nullableMessage + [JsonConstructor] public HealthCheckResult(string? nullableMessage = default) { NullableMessage = nullableMessage; @@ -50,7 +50,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +65,6 @@ namespace Org.OpenAPITools.Model 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 HealthCheckResult).AreEqual; - } - - /// - /// Returns true if HealthCheckResult instances are equal - /// - /// Instance of HealthCheckResult to be compared - /// Boolean - public bool Equals(HealthCheckResult? 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; - if (this.NullableMessage != null) - { - hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +76,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HealthCheckResult + /// + public class HealthCheckResultJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HealthCheckResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string nullableMessage = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "NullableMessage": + nullableMessage = reader.GetString(); + break; + default: + break; + } + } + } + + return new HealthCheckResult(nullableMessage); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index e207d964b03..00900bdaa52 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// IsoscelesTriangle /// - public partial class IsoscelesTriangle : IEquatable, IValidatableObject + public partial class IsoscelesTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -63,40 +63,6 @@ namespace Org.OpenAPITools.Model 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 IsoscelesTriangle).AreEqual; - } - - /// - /// Returns true if IsoscelesTriangle instances are equal - /// - /// Instance of IsoscelesTriangle to be compared - /// Boolean - public bool Equals(IsoscelesTriangle? 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,13 +79,6 @@ namespace Org.OpenAPITools.Model /// public class IsoscelesTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(IsoscelesTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -132,28 +91,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface? shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface? shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface? triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface? triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -168,6 +134,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs index af537950c8d..67fb97c53ab 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// List /// - public partial class List : IEquatable, IValidatableObject + public partial class List : IValidatableObject { /// /// Initializes a new instance of the class. /// /// _123list - public List(string? _123list = default) + [JsonConstructor] + public List(string _123list) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_123list == null) + throw new ArgumentNullException("_123list is a required property for List and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + _123List = _123list; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets _123List /// [JsonPropertyName("123-list")] - public string? _123List { get; set; } + public string _123List { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 List).AreEqual; - } - - /// - /// Returns true if List instances are equal - /// - /// Instance of List to be compared - /// Boolean - public bool Equals(List? 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; - if (this._123List != null) - { - hashCode = (hashCode * 59) + this._123List.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type List + /// + public class ListJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string _123list = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "123-list": + _123list = reader.GetString(); + break; + default: + break; + } + } + } + + return new List(_123list); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("123-list", list._123List); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs index f7ca7b5b607..63e92dcb241 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// Mammal /// - public partial class Mammal : IEquatable, IValidatableObject + public partial class Mammal : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Mammal(Whale whale) + [JsonConstructor] + internal Mammal(Whale whale) { Whale = whale; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Zebra zebra) + [JsonConstructor] + internal Mammal(Zebra zebra) { Zebra = zebra; } @@ -53,7 +54,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Pig pig) + [JsonConstructor] + internal Mammal(Pig pig) { Pig = pig; } @@ -61,23 +63,23 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Whale /// - public Whale Whale { get; set; } + public Whale? Whale { get; set; } /// /// Gets or Sets Zebra /// - public Zebra Zebra { get; set; } + public Zebra? Zebra { get; set; } /// /// Gets or Sets Pig /// - public Pig Pig { get; set; } + public Pig? Pig { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -91,44 +93,6 @@ namespace Org.OpenAPITools.Model 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 Mammal).AreEqual; - } - - /// - /// Returns true if Mammal instances are equal - /// - /// Instance of Mammal to be compared - /// Boolean - public bool Equals(Mammal? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -155,13 +119,6 @@ namespace Org.OpenAPITools.Model /// public class MammalJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Mammal).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -174,9 +131,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader whaleReader = reader; bool whaleDeserialized = Client.ClientUtils.TryDeserialize(ref whaleReader, options, out Whale? whale); @@ -189,16 +148,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -222,6 +186,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs index 64a3380a3d5..750572e0098 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,21 +28,40 @@ namespace Org.OpenAPITools.Model /// /// MapTest /// - public partial class MapTest : IEquatable, IValidatableObject + public partial class MapTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapMapOfString - /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary>? mapMapOfString = default, Dictionary? mapOfEnumString = default, Dictionary? directMap = default, Dictionary? indirectMap = default) + /// mapMapOfString + /// mapOfEnumString + [JsonConstructor] + public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) { - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapMapOfString == null) + throw new ArgumentNullException("mapMapOfString is a required property for MapTest and cannot be null."); + + if (mapOfEnumString == null) + throw new ArgumentNullException("mapOfEnumString is a required property for MapTest and cannot be null."); + + if (directMap == null) + throw new ArgumentNullException("directMap is a required property for MapTest and cannot be null."); + + if (indirectMap == null) + throw new ArgumentNullException("indirectMap is a required property for MapTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DirectMap = directMap; IndirectMap = indirectMap; + MapMapOfString = mapMapOfString; + MapOfEnumString = mapOfEnumString; } /// @@ -54,46 +72,77 @@ namespace Org.OpenAPITools.Model /// /// Enum UPPER for value: UPPER /// - [EnumMember(Value = "UPPER")] UPPER = 1, /// /// Enum Lower for value: lower /// - [EnumMember(Value = "lower")] Lower = 2 } /// - /// Gets or Sets MapMapOfString + /// Returns a InnerEnum /// - [JsonPropertyName("map_map_of_string")] - public Dictionary>? MapMapOfString { get; set; } + /// + /// + public static InnerEnum InnerEnumFromString(string value) + { + if (value == "UPPER") + return InnerEnum.UPPER; + + if (value == "lower") + return InnerEnum.Lower; + + throw new NotImplementedException($"Could not convert value to type InnerEnum: '{value}'"); + } /// - /// Gets or Sets MapOfEnumString + /// Returns equivalent json value /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary? MapOfEnumString { get; set; } + /// + /// + /// + 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; } + public Dictionary DirectMap { get; set; } /// /// Gets or Sets IndirectMap /// [JsonPropertyName("indirect_map")] - public Dictionary? IndirectMap { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -103,68 +152,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); - sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); - sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as MapTest).AreEqual; - } - - /// - /// Returns true if MapTest instances are equal - /// - /// Instance of MapTest to be compared - /// Boolean - public bool Equals(MapTest? 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; - if (this.MapMapOfString != null) - { - hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); - } - if (this.MapOfEnumString != null) - { - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); - } - if (this.DirectMap != null) - { - hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); - } - if (this.IndirectMap != null) - { - hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -176,4 +171,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MapTest + /// + public class MapTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MapTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary directMap = default; + Dictionary indirectMap = default; + Dictionary> mapMapOfString = default; + Dictionary mapOfEnumString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "direct_map": + directMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "indirect_map": + indirectMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_map_of_string": + mapMapOfString = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_of_enum_string": + mapOfEnumString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, options); + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, options); + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, options); + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index a583c8f393c..9086f808663 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,44 +28,60 @@ namespace Org.OpenAPITools.Model /// /// MixedPropertiesAndAdditionalPropertiesClass /// - public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid /// dateTime /// map - public MixedPropertiesAndAdditionalPropertiesClass(Guid? uuid = default, DateTime? dateTime = default, Dictionary? map = default) + /// uuid + [JsonConstructor] + public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid) { - Uuid = uuid; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (map == null) + throw new ArgumentNullException("map is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DateTime = dateTime; Map = map; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid? Uuid { get; set; } - /// /// Gets or Sets DateTime /// [JsonPropertyName("dateTime")] - public DateTime? DateTime { get; set; } + public DateTime DateTime { get; set; } /// /// Gets or Sets Map /// [JsonPropertyName("map")] - public Dictionary? Map { get; set; } + public Dictionary Map { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -76,63 +91,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 MixedPropertiesAndAdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal - /// - /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(MixedPropertiesAndAdditionalPropertiesClass? 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Map != null) - { - hashCode = (hashCode * 59) + this.Map.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -144,4 +109,83 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MixedPropertiesAndAdditionalPropertiesClass + /// + public class MixedPropertiesAndAdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + DateTime dateTime = default; + Dictionary map = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "map": + map = JsonSerializer.Deserialize>(ref reader, options); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.DateTime, options); + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, options); + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs index 318ef8a27a9..5ef23bad5fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,36 +28,49 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model name starting with number /// - public partial class Model200Response : IEquatable, IValidatableObject + public partial class Model200Response : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// classProperty /// name - /// _class - public Model200Response(int? name = default, string? _class = default) + [JsonConstructor] + public Model200Response(string classProperty, int name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for Model200Response and cannot be null."); + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for Model200Response and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; Name = name; - Class = _class; } + /// + /// Gets or Sets ClassProperty + /// + [JsonPropertyName("class")] + public string ClassProperty { get; set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public int? Name { get; set; } - - /// - /// Gets or Sets Class - /// - [JsonPropertyName("class")] - public string? Class { get; set; } + public int Name { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,55 +80,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Class: ").Append(Class).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 Model200Response).AreEqual; - } - - /// - /// Returns true if Model200Response instances are equal - /// - /// Instance of Model200Response to be compared - /// Boolean - public bool Equals(Model200Response? 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) + this.Name.GetHashCode(); - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -128,4 +97,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Model200Response + /// + public class Model200ResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Model200Response Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + int name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "class": + classProperty = reader.GetString(); + break; + case "name": + name = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Model200Response(classProperty, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("class", model200Response.ClassProperty); + writer.WriteNumber("name", (int)model200Response.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs index 86364761194..8dd430bc07d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,28 +28,38 @@ namespace Org.OpenAPITools.Model /// /// ModelClient /// - public partial class ModelClient : IEquatable, IValidatableObject + public partial class ModelClient : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _client - public ModelClient(string? _client = default) + /// clientProperty + [JsonConstructor] + public ModelClient(string clientProperty) { - _Client = _client; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (clientProperty == null) + throw new ArgumentNullException("clientProperty is a required property for ModelClient and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + _ClientProperty = clientProperty; } /// - /// Gets or Sets _Client + /// Gets or Sets _ClientProperty /// [JsonPropertyName("client")] - public string? _Client { get; set; } + public string _ClientProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -60,53 +69,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); - sb.Append(" _Client: ").Append(_Client).Append("\n"); + sb.Append(" _ClientProperty: ").Append(_ClientProperty).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 ModelClient).AreEqual; - } - - /// - /// Returns true if ModelClient instances are equal - /// - /// Instance of ModelClient to be compared - /// Boolean - public bool Equals(ModelClient? 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; - if (this._Client != null) - { - hashCode = (hashCode * 59) + this._Client.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ModelClient + /// + public class ModelClientJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ModelClient Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string clientProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "client": + clientProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ModelClient(clientProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("client", modelClient._ClientProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs index 3c560228d8d..2f0e11921ba 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,23 +28,39 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model name same as property name /// - public partial class Name : IEquatable, IValidatableObject + public partial class Name : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// nameProperty (required) - /// snakeCase + /// nameProperty /// property + /// snakeCase /// _123number - public Name(int nameProperty, int? snakeCase = default, string? property = default, int? _123number = default) + [JsonConstructor] + public Name(int nameProperty, string property, int snakeCase, int _123number) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (nameProperty == null) throw new ArgumentNullException("nameProperty is a required property for Name and cannot be null."); + if (snakeCase == null) + throw new ArgumentNullException("snakeCase is a required property for Name and cannot be null."); + + if (property == null) + throw new ArgumentNullException("property is a required property for Name and cannot be null."); + + if (_123number == null) + throw new ArgumentNullException("_123number is a required property for Name and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + NameProperty = nameProperty; - SnakeCase = snakeCase; Property = property; + SnakeCase = snakeCase; _123Number = _123number; } @@ -55,29 +70,29 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("name")] public int NameProperty { get; set; } - /// - /// Gets or Sets SnakeCase - /// - [JsonPropertyName("snake_case")] - public int? SnakeCase { get; private set; } - /// /// Gets or Sets Property /// [JsonPropertyName("property")] - public string? Property { get; set; } + public string Property { get; set; } + + /// + /// Gets or Sets SnakeCase + /// + [JsonPropertyName("snake_case")] + public int SnakeCase { get; } /// /// Gets or Sets _123Number /// [JsonPropertyName("123Number")] - public int? _123Number { get; private set; } + public int _123Number { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -88,8 +103,8 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" NameProperty: ").Append(NameProperty).Append("\n"); - sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" _123Number: ").Append(_123Number).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -125,21 +140,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + this.NameProperty.GetHashCode(); - hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); - if (this.Property != null) - { - hashCode = (hashCode * 59) + this.Property.GetHashCode(); - } - hashCode = (hashCode * 59) + this._123Number.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + _123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -151,4 +158,86 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Name + /// + public class NameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Name Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int nameProperty = default; + string property = default; + int snakeCase = default; + int _123number = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + nameProperty = reader.GetInt32(); + break; + case "property": + property = reader.GetString(); + break; + case "snake_case": + snakeCase = reader.GetInt32(); + break; + case "123Number": + _123number = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Name(nameProperty, property, snakeCase, _123number); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("name", (int)name.NameProperty); + writer.WriteString("property", name.Property); + writer.WriteNumber("snake_case", (int)name.SnakeCase); + writer.WriteNumber("123Number", (int)name._123Number); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs index 8b935f49408..8f79ed04ea6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,50 +28,75 @@ namespace Org.OpenAPITools.Model /// /// NullableClass /// - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// integerProp - /// numberProp + /// arrayItemsNullable + /// objectItemsNullable + /// arrayAndItemsNullableProp + /// arrayNullableProp /// booleanProp - /// stringProp /// dateProp /// datetimeProp - /// arrayNullableProp - /// arrayAndItemsNullableProp - /// arrayItemsNullable - /// objectNullableProp + /// integerProp + /// numberProp /// objectAndItemsNullableProp - /// objectItemsNullable - public NullableClass(int? integerProp = default, decimal? numberProp = default, bool? booleanProp = default, string? stringProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, List? arrayNullableProp = default, List? arrayAndItemsNullableProp = default, List? arrayItemsNullable = default, Dictionary? objectNullableProp = default, Dictionary? objectAndItemsNullableProp = default, Dictionary? objectItemsNullable = default) : base() + /// 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() { - IntegerProp = integerProp; - NumberProp = numberProp; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayItemsNullable == null) + throw new ArgumentNullException("arrayItemsNullable is a required property for NullableClass and cannot be null."); + + if (objectItemsNullable == null) + throw new ArgumentNullException("objectItemsNullable is a required property for NullableClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ArrayItemsNullable = arrayItemsNullable; + ObjectItemsNullable = objectItemsNullable; + ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + ArrayNullableProp = arrayNullableProp; BooleanProp = booleanProp; - StringProp = stringProp; DateProp = dateProp; DatetimeProp = datetimeProp; - ArrayNullableProp = arrayNullableProp; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayItemsNullable = arrayItemsNullable; - ObjectNullableProp = objectNullableProp; + IntegerProp = integerProp; + NumberProp = numberProp; ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectItemsNullable = objectItemsNullable; + ObjectNullableProp = objectNullableProp; + StringProp = stringProp; } /// - /// Gets or Sets IntegerProp + /// Gets or Sets ArrayItemsNullable /// - [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get; set; } /// - /// Gets or Sets NumberProp + /// Gets or Sets ObjectItemsNullable /// - [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + [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 @@ -80,12 +104,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("boolean_prop")] public bool? BooleanProp { get; set; } - /// - /// Gets or Sets StringProp - /// - [JsonPropertyName("string_prop")] - public string? StringProp { get; set; } - /// /// Gets or Sets DateProp /// @@ -99,28 +117,16 @@ namespace Org.OpenAPITools.Model public DateTime? DatetimeProp { get; set; } /// - /// Gets or Sets ArrayNullableProp + /// Gets or Sets IntegerProp /// - [JsonPropertyName("array_nullable_prop")] - public List? ArrayNullableProp { get; set; } + [JsonPropertyName("integer_prop")] + public int? IntegerProp { get; set; } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Gets or Sets NumberProp /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List? ArrayAndItemsNullableProp { get; set; } - - /// - /// Gets or Sets ArrayItemsNullable - /// - [JsonPropertyName("array_items_nullable")] - public List? ArrayItemsNullable { get; set; } - - /// - /// Gets or Sets ObjectNullableProp - /// - [JsonPropertyName("object_nullable_prop")] - public Dictionary? ObjectNullableProp { get; set; } + [JsonPropertyName("number_prop")] + public decimal? NumberProp { get; set; } /// /// Gets or Sets ObjectAndItemsNullableProp @@ -129,10 +135,16 @@ namespace Org.OpenAPITools.Model public Dictionary? ObjectAndItemsNullableProp { get; set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ObjectNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary? ObjectItemsNullable { get; set; } + [JsonPropertyName("object_nullable_prop")] + public Dictionary? ObjectNullableProp { get; set; } + + /// + /// Gets or Sets StringProp + /// + [JsonPropertyName("string_prop")] + public string? StringProp { get; set; } /// /// Returns the string presentation of the object @@ -143,103 +155,21 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); - sb.Append(" NumberProp: ").Append(NumberProp).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(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); - sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); - sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).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(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" StringProp: ").Append(StringProp).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 NullableClass).AreEqual; - } - - /// - /// Returns true if NullableClass instances are equal - /// - /// Instance of NullableClass to be compared - /// Boolean - public bool Equals(NullableClass? 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 = base.GetHashCode(); - if (this.IntegerProp != null) - { - hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); - } - if (this.NumberProp != null) - { - hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); - } - if (this.BooleanProp != null) - { - hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); - } - if (this.StringProp != null) - { - hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); - } - if (this.DateProp != null) - { - hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); - } - if (this.DatetimeProp != null) - { - hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); - } - if (this.ArrayNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); - } - if (this.ArrayAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); - } - if (this.ArrayItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); - } - if (this.ObjectNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); - } - if (this.ObjectAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); - } - if (this.ObjectItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -251,4 +181,145 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NullableClass + /// + public class NullableClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NullableClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_items_nullable": + arrayItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_items_nullable": + objectItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_and_items_nullable_prop": + arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_nullable_prop": + arrayNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "boolean_prop": + booleanProp = reader.GetBoolean(); + break; + case "date_prop": + dateProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "datetime_prop": + datetimeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "integer_prop": + if (reader.TokenType != JsonTokenType.Null) + integerProp = reader.GetInt32(); + break; + case "number_prop": + if (reader.TokenType != JsonTokenType.Null) + numberProp = reader.GetInt32(); + break; + case "object_and_items_nullable_prop": + objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_nullable_prop": + objectNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "string_prop": + stringProp = reader.GetString(); + break; + default: + break; + } + } + } + + return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, options); + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, options); + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, options); + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, options); + if (nullableClass.BooleanProp != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); + else + writer.WriteNull("boolean_prop"); + writer.WritePropertyName("date_prop"); + JsonSerializer.Serialize(writer, nullableClass.DateProp, options); + writer.WritePropertyName("datetime_prop"); + JsonSerializer.Serialize(writer, nullableClass.DatetimeProp, options); + if (nullableClass.IntegerProp != null) + writer.WriteNumber("integer_prop", (int)nullableClass.IntegerProp.Value); + else + writer.WriteNull("integer_prop"); + if (nullableClass.NumberProp != null) + writer.WriteNumber("number_prop", (int)nullableClass.NumberProp.Value); + else + writer.WriteNull("number_prop"); + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, options); + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, options); + writer.WriteString("string_prop", nullableClass.StringProp); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs index f5eb1bcd8ec..59d13aaff1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class NullableShape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public NullableShape(Triangle triangle) + [JsonConstructor] + internal NullableShape(Triangle triangle) { Triangle = triangle; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public NullableShape(Quadrilateral quadrilateral) + [JsonConstructor] + internal NullableShape(Quadrilateral quadrilateral) { Quadrilateral = quadrilateral; } @@ -52,18 +53,18 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Triangle /// - public Triangle Triangle { get; set; } + public Triangle? Triangle { get; set; } /// /// Gets or Sets Quadrilateral /// - public Quadrilateral Quadrilateral { get; set; } + public Quadrilateral? Quadrilateral { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -77,44 +78,6 @@ namespace Org.OpenAPITools.Model 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 NullableShape).AreEqual; - } - - /// - /// Returns true if NullableShape instances are equal - /// - /// Instance of NullableShape to be compared - /// Boolean - public bool Equals(NullableShape? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,13 +104,6 @@ namespace Org.OpenAPITools.Model /// public class NullableShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(NullableShape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -160,9 +116,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle? triangle); @@ -172,16 +130,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -202,6 +165,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs index 6f413c0fca2..74e98b9b321 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// NumberOnly /// - public partial class NumberOnly : IEquatable, IValidatableObject + public partial class NumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// justNumber - public NumberOnly(decimal? justNumber = default) + [JsonConstructor] + public NumberOnly(decimal justNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justNumber == null) + throw new ArgumentNullException("justNumber is a required property for NumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + JustNumber = justNumber; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets JustNumber /// [JsonPropertyName("JustNumber")] - public decimal? JustNumber { get; set; } + public decimal JustNumber { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,45 +74,6 @@ namespace Org.OpenAPITools.Model 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 NumberOnly).AreEqual; - } - - /// - /// Returns true if NumberOnly instances are equal - /// - /// Instance of NumberOnly to be compared - /// Boolean - public bool Equals(NumberOnly? 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) + this.JustNumber.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NumberOnly + /// + public class NumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal justNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "JustNumber": + justNumber = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new NumberOnly(justNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("JustNumber", (int)numberOnly.JustNumber); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index bcaaa473035..1e365b2c6d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,55 +28,74 @@ namespace Org.OpenAPITools.Model /// /// ObjectWithDeprecatedFields /// - public partial class ObjectWithDeprecatedFields : IEquatable, IValidatableObject + public partial class ObjectWithDeprecatedFields : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid - /// id - /// deprecatedRef /// bars - public ObjectWithDeprecatedFields(string? uuid = default, decimal? id = default, DeprecatedObject? deprecatedRef = default, List? bars = default) + /// deprecatedRef + /// id + /// uuid + [JsonConstructor] + public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) { - Uuid = uuid; - Id = id; - DeprecatedRef = deprecatedRef; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (id == null) + throw new ArgumentNullException("id is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (deprecatedRef == null) + throw new ArgumentNullException("deprecatedRef is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (bars == null) + throw new ArgumentNullException("bars is a required property for ObjectWithDeprecatedFields and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bars = bars; + DeprecatedRef = deprecatedRef; + Id = id; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public string? Uuid { get; set; } - - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - [Obsolete] - public decimal? Id { get; set; } - - /// - /// Gets or Sets DeprecatedRef - /// - [JsonPropertyName("deprecatedRef")] - [Obsolete] - public DeprecatedObject? DeprecatedRef { get; set; } - /// /// Gets or Sets Bars /// [JsonPropertyName("bars")] [Obsolete] - public List? Bars { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -87,65 +105,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" DeprecatedRef: ").Append(DeprecatedRef).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ObjectWithDeprecatedFields).AreEqual; - } - - /// - /// Returns true if ObjectWithDeprecatedFields instances are equal - /// - /// Instance of ObjectWithDeprecatedFields to be compared - /// Boolean - public bool Equals(ObjectWithDeprecatedFields? 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.DeprecatedRef != null) - { - hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); - } - if (this.Bars != null) - { - hashCode = (hashCode * 59) + this.Bars.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -157,4 +124,88 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ObjectWithDeprecatedFields + /// + public class ObjectWithDeprecatedFieldsJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List bars = default; + DeprecatedObject deprecatedRef = default; + decimal id = default; + string uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bars": + bars = JsonSerializer.Deserialize>(ref reader, options); + break; + case "deprecatedRef": + deprecatedRef = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt32(); + break; + case "uuid": + uuid = reader.GetString(); + break; + default: + break; + } + } + } + + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, options); + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, options); + writer.WriteNumber("id", (int)objectWithDeprecatedFields.Id); + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs index 14f4d8e4b88..9d1751019bd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,7 +28,7 @@ namespace Org.OpenAPITools.Model /// /// Order /// - public partial class Order : IEquatable, IValidatableObject + public partial class Order : IValidatableObject { /// /// Initializes a new instance of the class. @@ -40,8 +39,33 @@ namespace Org.OpenAPITools.Model /// shipDate /// Order Status /// complete (default to false) - public Order(long? id = default, long? petId = default, int? quantity = default, DateTime? shipDate = default, StatusEnum? status = default, bool? complete = false) + [JsonConstructor] + public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Order and cannot be null."); + + if (petId == null) + throw new ArgumentNullException("petId is a required property for Order and cannot be null."); + + if (quantity == null) + throw new ArgumentNullException("quantity is a required property for Order and cannot be null."); + + if (shipDate == null) + throw new ArgumentNullException("shipDate is a required property for Order and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Order and cannot be null."); + + if (complete == null) + throw new ArgumentNullException("complete is a required property for Order and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; PetId = petId; Quantity = quantity; @@ -59,65 +83,101 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "placed") + return StatusEnum.Placed; + + if (value == "approved") + return StatusEnum.Approved; + + if (value == "delivered") + return StatusEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } + public StatusEnum Status { get; set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long? Id { get; set; } + public long Id { get; set; } /// /// Gets or Sets PetId /// [JsonPropertyName("petId")] - public long? PetId { get; set; } + public long PetId { get; set; } /// /// Gets or Sets Quantity /// [JsonPropertyName("quantity")] - public int? Quantity { get; set; } + public int Quantity { get; set; } /// /// Gets or Sets ShipDate /// [JsonPropertyName("shipDate")] - public DateTime? ShipDate { get; set; } + public DateTime ShipDate { get; set; } /// /// Gets or Sets Complete /// [JsonPropertyName("complete")] - public bool? Complete { get; set; } + public bool Complete { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -137,53 +197,6 @@ namespace Org.OpenAPITools.Model 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 Order).AreEqual; - } - - /// - /// Returns true if Order instances are equal - /// - /// Instance of Order to be compared - /// Boolean - public bool Equals(Order? 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) + this.Id.GetHashCode(); - hashCode = (hashCode * 59) + this.PetId.GetHashCode(); - hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); - if (this.ShipDate != null) - { - hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - hashCode = (hashCode * 59) + this.Complete.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -195,4 +208,102 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Order + /// + public class OrderJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Order Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + long petId = default; + int quantity = default; + DateTime shipDate = default; + Order.StatusEnum status = default; + bool complete = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "petId": + petId = reader.GetInt64(); + break; + case "quantity": + quantity = reader.GetInt32(); + break; + case "shipDate": + shipDate = JsonSerializer.Deserialize(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Order.StatusEnumFromString(statusRawValue); + break; + case "complete": + complete = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Order(id, petId, quantity, shipDate, status, complete); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)order.Id); + writer.WriteNumber("petId", (int)order.PetId); + writer.WriteNumber("quantity", (int)order.Quantity); + writer.WritePropertyName("shipDate"); + JsonSerializer.Serialize(writer, order.ShipDate, options); + var statusRawValue = Order.StatusEnumToJsonValue(order.Status); + if (statusRawValue != null) + writer.WriteString("status", statusRawValue); + else + writer.WriteNull("status"); + writer.WriteBoolean("complete", order.Complete); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs index f4d199456b2..337e12f7c1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,44 +28,60 @@ namespace Org.OpenAPITools.Model /// /// OuterComposite /// - public partial class OuterComposite : IEquatable, IValidatableObject + public partial class OuterComposite : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// myBoolean /// myNumber /// myString - /// myBoolean - public OuterComposite(decimal? myNumber = default, string? myString = default, bool? myBoolean = default) + [JsonConstructor] + public OuterComposite(bool myBoolean, decimal myNumber, string myString) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (myNumber == null) + throw new ArgumentNullException("myNumber is a required property for OuterComposite and cannot be null."); + + if (myString == null) + throw new ArgumentNullException("myString is a required property for OuterComposite and cannot be null."); + + if (myBoolean == null) + throw new ArgumentNullException("myBoolean is a required property for OuterComposite and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + MyBoolean = myBoolean; MyNumber = myNumber; MyString = myString; - MyBoolean = myBoolean; } - /// - /// 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 MyBoolean /// [JsonPropertyName("my_boolean")] - public bool? MyBoolean { get; set; } + 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -76,57 +91,13 @@ namespace Org.OpenAPITools.Model { 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(" MyBoolean: ").Append(MyBoolean).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 OuterComposite).AreEqual; - } - - /// - /// Returns true if OuterComposite instances are equal - /// - /// Instance of OuterComposite to be compared - /// Boolean - public bool Equals(OuterComposite? 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) + this.MyNumber.GetHashCode(); - if (this.MyString != null) - { - hashCode = (hashCode * 59) + this.MyString.GetHashCode(); - } - hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -138,4 +109,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type OuterComposite + /// + public class OuterCompositeJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override OuterComposite Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool myBoolean = default; + decimal myNumber = default; + string myString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "my_boolean": + myBoolean = reader.GetBoolean(); + break; + case "my_number": + myNumber = reader.GetInt32(); + break; + case "my_string": + myString = reader.GetString(); + break; + default: + break; + } + } + } + + return new OuterComposite(myBoolean, myNumber, myString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); + writer.WriteNumber("my_number", (int)outerComposite.MyNumber); + writer.WriteString("my_string", outerComposite.MyString); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs index 8a82c640206..da207e91826 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,20 +33,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumConverter : JsonConverter + { + public static OuterEnum FromString(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnum: '{value}'"); + } + + public static OuterEnum? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnum? result = OuterEnumConverter.FromString(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()); + } + } + + public class OuterEnumNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnum from the Json object + /// + /// + /// + /// + /// + public override OuterEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnum? result = OuterEnumConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index edee8308283..039b5e9cd39 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,20 +33,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumDefaultValueConverter : JsonConverter + { + public static OuterEnumDefaultValue FromString(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnumDefaultValue: '{value}'"); + } + + public static OuterEnumDefaultValue? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index b1e9dc142e3..7878340efd1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -47,4 +46,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerConverter : JsonConverter + { + public static OuterEnumInteger FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumInteger: '{value}'"); + } + + public static OuterEnumInteger? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumInteger value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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()); + } + } + + public class OuterEnumIntegerNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumInteger from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index 1167271da6e..a64d3596f3c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -47,4 +46,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerDefaultValueConverter : JsonConverter + { + public static OuterEnumIntegerDefaultValue FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumIntegerDefaultValue: '{value}'"); + } + + public static OuterEnumIntegerDefaultValue? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumIntegerDefaultValue value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumIntegerDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumIntegerDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs index 58475dcfe23..75b8e364491 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// ParentPet /// - public partial class ParentPet : GrandparentAnimal, IEquatable + public partial class ParentPet : GrandparentAnimal, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) - public ParentPet(string petType) : base(petType) + /// petType + [JsonConstructor] + internal ParentPet(string petType) : base(petType) { } @@ -51,40 +51,6 @@ namespace Org.OpenAPITools.Model 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 ParentPet).AreEqual; - } - - /// - /// Returns true if ParentPet instances are equal - /// - /// Instance of ParentPet to be compared - /// Boolean - public bool Equals(ParentPet? 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -92,13 +58,6 @@ namespace Org.OpenAPITools.Model /// public class ParentPetJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ParentPet).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -111,17 +70,22 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); - string? petType = default; + JsonTokenType startingTokenType = reader.TokenType; + + string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -131,6 +95,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -145,6 +111,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", parentPet.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs index 1694a5311ec..616786dd13e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,31 +28,50 @@ namespace Org.OpenAPITools.Model /// /// Pet /// - public partial class Pet : IEquatable, IValidatableObject + public partial class Pet : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) - /// photoUrls (required) - /// id /// category - /// tags + /// id + /// name + /// photoUrls /// pet status in the store - public Pet(string name, List photoUrls, long? id = default, Category? category = default, List? tags = default, StatusEnum? status = default) + /// tags + [JsonConstructor] + public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Pet and cannot be null."); + + if (category == null) + throw new ArgumentNullException("category is a required property for Pet and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Pet and cannot be null."); if (photoUrls == null) throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null."); + if (tags == null) + throw new ArgumentNullException("tags is a required property for Pet and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Pet and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Category = category; + Id = id; Name = name; PhotoUrls = photoUrls; - Id = id; - Category = category; - Tags = tags; Status = status; + Tags = tags; } /// @@ -65,29 +83,77 @@ namespace Org.OpenAPITools.Model /// /// Enum Available for value: available /// - [EnumMember(Value = "available")] Available = 1, /// /// Enum Pending for value: pending /// - [EnumMember(Value = "pending")] Pending = 2, /// /// Enum Sold for value: sold /// - [EnumMember(Value = "sold")] Sold = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "available") + return StatusEnum.Available; + + if (value == "pending") + return StatusEnum.Pending; + + if (value == "sold") + return StatusEnum.Sold; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } + 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 @@ -101,29 +167,17 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("photoUrls")] public List PhotoUrls { get; set; } - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - public long? Id { get; set; } - - /// - /// Gets or Sets Category - /// - [JsonPropertyName("category")] - public Category? Category { get; set; } - /// /// Gets or Sets Tags /// [JsonPropertyName("tags")] - public List? Tags { get; set; } + public List Tags { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -133,72 +187,16 @@ namespace Org.OpenAPITools.Model { 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(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Tags: ").Append(Tags).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Pet).AreEqual; - } - - /// - /// Returns true if Pet instances are equal - /// - /// Instance of Pet to be compared - /// Boolean - public bool Equals(Pet? 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.PhotoUrls != null) - { - hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.Category != null) - { - hashCode = (hashCode * 59) + this.Category.GetHashCode(); - } - if (this.Tags != null) - { - hashCode = (hashCode * 59) + this.Tags.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -210,4 +208,104 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Pet + /// + public class PetJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Pet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Category category = default; + long id = default; + string name = default; + List photoUrls = default; + Pet.StatusEnum status = default; + List tags = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "category": + category = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + case "photoUrls": + photoUrls = JsonSerializer.Deserialize>(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Pet.StatusEnumFromString(statusRawValue); + break; + case "tags": + tags = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new Pet(category, id, name, photoUrls, status, tags); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, options); + writer.WriteNumber("id", (int)pet.Id); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); + JsonSerializer.Serialize(writer, pet.PhotoUrls, options); + 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, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs index e80f7c4c372..94f70a36a33 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// Pig /// - public partial class Pig : IEquatable, IValidatableObject + public partial class Pig : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Pig(BasquePig basquePig) + [JsonConstructor] + internal Pig(BasquePig basquePig) { BasquePig = basquePig; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Pig(DanishPig danishPig) + [JsonConstructor] + internal Pig(DanishPig danishPig) { DanishPig = danishPig; } @@ -52,18 +53,18 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets BasquePig /// - public BasquePig BasquePig { get; set; } + public BasquePig? BasquePig { get; set; } /// /// Gets or Sets DanishPig /// - public DanishPig DanishPig { get; set; } + public DanishPig? DanishPig { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -77,44 +78,6 @@ namespace Org.OpenAPITools.Model 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 Pig).AreEqual; - } - - /// - /// Returns true if Pig instances are equal - /// - /// Instance of Pig to be compared - /// Boolean - public bool Equals(Pig? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,13 +104,6 @@ namespace Org.OpenAPITools.Model /// public class PigJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Pig).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -160,9 +116,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader basquePigReader = reader; bool basquePigDeserialized = Client.ClientUtils.TryDeserialize(ref basquePigReader, options, out BasquePig? basquePig); @@ -172,16 +130,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -202,6 +165,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index b9bc60379ae..a58cc27f945 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// PolymorphicProperty /// - public partial class PolymorphicProperty : IEquatable, IValidatableObject + public partial class PolymorphicProperty : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(bool _bool) + [JsonConstructor] + internal PolymorphicProperty(bool _bool) { Bool = _bool; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(string _string) + [JsonConstructor] + internal PolymorphicProperty(string _string) { String = _string; } @@ -53,7 +54,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(Object _object) + [JsonConstructor] + internal PolymorphicProperty(Object _object) { Object = _object; } @@ -62,7 +64,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(List liststring) + [JsonConstructor] + internal PolymorphicProperty(List liststring) { Liststring = liststring; } @@ -70,28 +73,28 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Bool /// - public bool Bool { get; set; } + public bool? Bool { get; set; } /// /// Gets or Sets String /// - public string String { get; set; } + public string? String { get; set; } /// /// Gets or Sets Object /// - public Object Object { get; set; } + public Object? Object { get; set; } /// /// Gets or Sets Liststring /// - public List Liststring { get; set; } + public List? Liststring { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -105,44 +108,6 @@ namespace Org.OpenAPITools.Model 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 PolymorphicProperty).AreEqual; - } - - /// - /// Returns true if PolymorphicProperty instances are equal - /// - /// Instance of PolymorphicProperty to be compared - /// Boolean - public bool Equals(PolymorphicProperty? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -159,13 +124,6 @@ namespace Org.OpenAPITools.Model /// public class PolymorphicPropertyJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(PolymorphicProperty).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -178,9 +136,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader _boolReader = reader; bool _boolDeserialized = Client.ClientUtils.TryDeserialize(ref _boolReader, options, out bool _bool); @@ -196,16 +156,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -232,6 +197,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs index ba1b3e01773..51a2353b1ba 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,13 +28,14 @@ namespace Org.OpenAPITools.Model /// /// Quadrilateral /// - public partial class Quadrilateral : IEquatable, IValidatableObject + public partial class Quadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) + [JsonConstructor] + internal Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) { SimpleQuadrilateral = simpleQuadrilateral; } @@ -44,7 +44,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Quadrilateral(ComplexQuadrilateral complexQuadrilateral) + [JsonConstructor] + internal Quadrilateral(ComplexQuadrilateral complexQuadrilateral) { ComplexQuadrilateral = complexQuadrilateral; } @@ -52,18 +53,18 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets SimpleQuadrilateral /// - public SimpleQuadrilateral SimpleQuadrilateral { get; set; } + public SimpleQuadrilateral? SimpleQuadrilateral { get; set; } /// /// Gets or Sets ComplexQuadrilateral /// - public ComplexQuadrilateral ComplexQuadrilateral { get; set; } + public ComplexQuadrilateral? ComplexQuadrilateral { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -77,44 +78,6 @@ namespace Org.OpenAPITools.Model 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 Quadrilateral).AreEqual; - } - - /// - /// Returns true if Quadrilateral instances are equal - /// - /// Instance of Quadrilateral to be compared - /// Boolean - public bool Equals(Quadrilateral? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,13 +104,6 @@ namespace Org.OpenAPITools.Model /// public class QuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Quadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -160,9 +116,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader simpleQuadrilateralReader = reader; bool simpleQuadrilateralDeserialized = Client.ClientUtils.TryDeserialize(ref simpleQuadrilateralReader, options, out SimpleQuadrilateral? simpleQuadrilateral); @@ -172,16 +130,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -202,6 +165,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 0aadff208b8..164f877885b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// QuadrilateralInterface /// - public partial class QuadrilateralInterface : IEquatable, IValidatableObject + public partial class QuadrilateralInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public QuadrilateralInterface(string quadrilateralType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) throw new ArgumentNullException("quadrilateralType is a required property for QuadrilateralInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + QuadrilateralType = quadrilateralType; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 QuadrilateralInterface).AreEqual; - } - - /// - /// Returns true if QuadrilateralInterface instances are equal - /// - /// Instance of QuadrilateralInterface to be compared - /// Boolean - public bool Equals(QuadrilateralInterface? 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -121,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type QuadrilateralInterface + /// + public class QuadrilateralInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override QuadrilateralInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string quadrilateralType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "quadrilateralType": + quadrilateralType = reader.GetString(); + break; + default: + break; + } + } + } + + return new QuadrilateralInterface(quadrilateralType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 431c19694ab..55936865c04 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// ReadOnlyFirst /// - public partial class ReadOnlyFirst : IEquatable, IValidatableObject + public partial class ReadOnlyFirst : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// bar /// baz - public ReadOnlyFirst(string? bar = default, string? baz = default) + [JsonConstructor] + public ReadOnlyFirst(string bar, string baz) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for ReadOnlyFirst and cannot be null."); + + if (baz == null) + throw new ArgumentNullException("baz is a required property for ReadOnlyFirst and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Baz = baz; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string? Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Baz /// [JsonPropertyName("baz")] - public string? Baz { get; set; } + public string Baz { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -104,22 +116,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Baz != null) - { - hashCode = (hashCode * 59) + this.Baz.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -131,4 +133,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ReadOnlyFirst + /// + public class ReadOnlyFirstJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ReadOnlyFirst Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string baz = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "baz": + baz = reader.GetString(); + break; + default: + break; + } + } + } + + return new ReadOnlyFirst(bar, baz); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", readOnlyFirst.Bar); + writer.WriteString("baz", readOnlyFirst.Baz); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs index 9c1b60d8791..7007eff776c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,24 @@ namespace Org.OpenAPITools.Model /// /// Model for testing reserved words /// - public partial class Return : IEquatable, IValidatableObject + public partial class Return : IValidatableObject { /// /// Initializes a new instance of the class. /// /// returnProperty - public Return(int? returnProperty = default) + [JsonConstructor] + public Return(int returnProperty) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (returnProperty == null) + throw new ArgumentNullException("returnProperty is a required property for Return and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ReturnProperty = returnProperty; } @@ -44,13 +53,13 @@ namespace Org.OpenAPITools.Model /// Gets or Sets ReturnProperty /// [JsonPropertyName("return")] - public int? ReturnProperty { get; set; } + public int ReturnProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -65,45 +74,6 @@ namespace Org.OpenAPITools.Model 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 Return).AreEqual; - } - - /// - /// Returns true if Return instances are equal - /// - /// Instance of Return to be compared - /// Boolean - public bool Equals(Return? 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) + this.ReturnProperty.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Return + /// + public class ReturnJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Return Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int returnProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "return": + returnProperty = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Return(returnProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Return _return, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("return", (int)_return.ReturnProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 6fcceeb2426..3d964b902c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// ScaleneTriangle /// - public partial class ScaleneTriangle : IEquatable, IValidatableObject + public partial class ScaleneTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -70,44 +70,6 @@ namespace Org.OpenAPITools.Model 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 ScaleneTriangle).AreEqual; - } - - /// - /// Returns true if ScaleneTriangle instances are equal - /// - /// Instance of ScaleneTriangle to be compared - /// Boolean - public bool Equals(ScaleneTriangle? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +86,6 @@ namespace Org.OpenAPITools.Model /// public class ScaleneTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ScaleneTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,28 +98,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface? shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface? shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface? triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface? triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +141,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs index 5f34a452323..eaa601f77fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// Shape /// - public partial class Shape : IEquatable, IValidatableObject + public partial class Shape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -49,11 +55,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -62,12 +75,12 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Triangle /// - public Triangle Triangle { get; set; } + public Triangle? Triangle { get; set; } /// /// Gets or Sets Quadrilateral /// - public Quadrilateral Quadrilateral { get; set; } + public Quadrilateral? Quadrilateral { get; set; } /// /// Gets or Sets QuadrilateralType @@ -79,7 +92,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -94,48 +107,6 @@ namespace Org.OpenAPITools.Model 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 Shape).AreEqual; - } - - /// - /// Returns true if Shape instances are equal - /// - /// Instance of Shape to be compared - /// Boolean - public bool Equals(Shape? 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -162,13 +133,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Shape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -181,23 +145,28 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle? triangle); Utf8JsonReader quadrilateralReader = reader; bool quadrilateralDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralReader, options, out Quadrilateral? quadrilateral); - string? quadrilateralType = default; + string quadrilateralType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -207,6 +176,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -227,6 +198,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shape.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs index 37871f3dc2a..e526918eec7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// ShapeInterface /// - public partial class ShapeInterface : IEquatable, IValidatableObject + public partial class ShapeInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// shapeType (required) + /// shapeType + [JsonConstructor] public ShapeInterface(string shapeType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) throw new ArgumentNullException("shapeType is a required property for ShapeInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ShapeType = shapeType; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 ShapeInterface).AreEqual; - } - - /// - /// Returns true if ShapeInterface instances are equal - /// - /// Instance of ShapeInterface to be compared - /// Boolean - public bool Equals(ShapeInterface? 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -121,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ShapeInterface + /// + public class ShapeInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ShapeInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string shapeType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "shapeType": + shapeType = reader.GetString(); + break; + default: + break; + } + } + } + + return new ShapeInterface(shapeType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", shapeInterface.ShapeType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 171347cda27..ce6ae1c2a0c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. /// - public partial class ShapeOrNull : IEquatable, IValidatableObject + public partial class ShapeOrNull : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -49,11 +55,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -62,12 +75,12 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Triangle /// - public Triangle Triangle { get; set; } + public Triangle? Triangle { get; set; } /// /// Gets or Sets Quadrilateral /// - public Quadrilateral Quadrilateral { get; set; } + public Quadrilateral? Quadrilateral { get; set; } /// /// Gets or Sets QuadrilateralType @@ -79,7 +92,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -94,48 +107,6 @@ namespace Org.OpenAPITools.Model 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 ShapeOrNull).AreEqual; - } - - /// - /// Returns true if ShapeOrNull instances are equal - /// - /// Instance of ShapeOrNull to be compared - /// Boolean - public bool Equals(ShapeOrNull? 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -162,13 +133,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeOrNullJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ShapeOrNull).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -181,23 +145,28 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle? triangle); Utf8JsonReader quadrilateralReader = reader; bool quadrilateralDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralReader, options, out Quadrilateral? quadrilateral); - string? quadrilateralType = default; + string quadrilateralType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -207,6 +176,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -227,6 +198,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shapeOrNull.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index d5565e094cc..c92989e1333 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,14 +28,15 @@ namespace Org.OpenAPITools.Model /// /// SimpleQuadrilateral /// - public partial class SimpleQuadrilateral : IEquatable, IValidatableObject + public partial class SimpleQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -70,44 +70,6 @@ namespace Org.OpenAPITools.Model 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 SimpleQuadrilateral).AreEqual; - } - - /// - /// Returns true if SimpleQuadrilateral instances are equal - /// - /// Instance of SimpleQuadrilateral to be compared - /// Boolean - public bool Equals(SimpleQuadrilateral? 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +86,6 @@ namespace Org.OpenAPITools.Model /// public class SimpleQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(SimpleQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,28 +98,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface? shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface? shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface? quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface? quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +141,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs index 6d7d21215bc..b1e359b5776 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,36 +28,49 @@ namespace Org.OpenAPITools.Model /// /// SpecialModelName /// - public partial class SpecialModelName : IEquatable, IValidatableObject + public partial class SpecialModelName : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// specialPropertyName /// specialModelNameProperty - public SpecialModelName(long? specialPropertyName = default, string? specialModelNameProperty = default) + /// specialPropertyName + [JsonConstructor] + public SpecialModelName(string specialModelNameProperty, long specialPropertyName) { - SpecialPropertyName = specialPropertyName; - SpecialModelNameProperty = specialModelNameProperty; - } +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - /// - /// Gets or Sets SpecialPropertyName - /// - [JsonPropertyName("$special[property.name]")] - public long? SpecialPropertyName { get; set; } + if (specialPropertyName == null) + throw new ArgumentNullException("specialPropertyName is a required property for SpecialModelName and cannot be null."); + + if (specialModelNameProperty == null) + throw new ArgumentNullException("specialModelNameProperty is a required property for SpecialModelName and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + SpecialModelNameProperty = specialModelNameProperty; + SpecialPropertyName = specialPropertyName; + } /// /// Gets or Sets SpecialModelNameProperty /// [JsonPropertyName("_special_model.name_")] - public string? SpecialModelNameProperty { get; set; } + public string SpecialModelNameProperty { 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,55 +80,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); - sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" SpecialModelNameProperty: ").Append(SpecialModelNameProperty).Append("\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).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 SpecialModelName).AreEqual; - } - - /// - /// Returns true if SpecialModelName instances are equal - /// - /// Instance of SpecialModelName to be compared - /// Boolean - public bool Equals(SpecialModelName? 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) + this.SpecialPropertyName.GetHashCode(); - if (this.SpecialModelNameProperty != null) - { - hashCode = (hashCode * 59) + this.SpecialModelNameProperty.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -128,4 +97,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type SpecialModelName + /// + public class SpecialModelNameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override SpecialModelName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string specialModelNameProperty = default; + long specialPropertyName = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_special_model.name_": + specialModelNameProperty = reader.GetString(); + break; + case "$special[property.name]": + specialPropertyName = reader.GetInt64(); + break; + default: + break; + } + } + } + + return new SpecialModelName(specialModelNameProperty, specialPropertyName); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_special_model.name_", specialModelName.SpecialModelNameProperty); + writer.WriteNumber("$special[property.name]", (int)specialModelName.SpecialPropertyName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs index 69236717eb8..7f02e8846fe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,15 +28,28 @@ namespace Org.OpenAPITools.Model /// /// Tag /// - public partial class Tag : IEquatable, IValidatableObject + public partial class Tag : IValidatableObject { /// /// Initializes a new instance of the class. /// /// id /// name - public Tag(long? id = default, string? name = default) + [JsonConstructor] + public Tag(long id, string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Tag and cannot be null."); + + if (name == null) + throw new ArgumentNullException("name is a required property for Tag and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; Name = name; } @@ -46,19 +58,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Id /// [JsonPropertyName("id")] - public long? Id { get; set; } + public long Id { get; set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string? Name { get; set; } + public string Name { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,49 +86,6 @@ namespace Org.OpenAPITools.Model 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 Tag).AreEqual; - } - - /// - /// Returns true if Tag instances are equal - /// - /// Instance of Tag to be compared - /// Boolean - public bool Equals(Tag? 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) + this.Id.GetHashCode(); - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -128,4 +97,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Tag + /// + public class TagJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Tag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Tag(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)tag.Id); + writer.WriteString("name", tag.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs index 5d502172b9e..0c9ca60f658 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,21 +28,28 @@ namespace Org.OpenAPITools.Model /// /// Triangle /// - public partial class Triangle : IEquatable, IValidatableObject + public partial class Triangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(EquilateralTriangle equilateralTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' EquilateralTriangle = equilateralTriangle; ShapeType = shapeType; @@ -54,15 +60,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(IsoscelesTriangle isoscelesTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' IsoscelesTriangle = isoscelesTriangle; ShapeType = shapeType; @@ -73,15 +86,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(ScaleneTriangle scaleneTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' ScaleneTriangle = scaleneTriangle; ShapeType = shapeType; @@ -91,17 +111,17 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EquilateralTriangle /// - public EquilateralTriangle EquilateralTriangle { get; set; } + public EquilateralTriangle? EquilateralTriangle { get; set; } /// /// Gets or Sets IsoscelesTriangle /// - public IsoscelesTriangle IsoscelesTriangle { get; set; } + public IsoscelesTriangle? IsoscelesTriangle { get; set; } /// /// Gets or Sets ScaleneTriangle /// - public ScaleneTriangle ScaleneTriangle { get; set; } + public ScaleneTriangle? ScaleneTriangle { get; set; } /// /// Gets or Sets ShapeType @@ -119,7 +139,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -135,52 +155,6 @@ namespace Org.OpenAPITools.Model 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 Triangle).AreEqual; - } - - /// - /// Returns true if Triangle instances are equal - /// - /// Instance of Triangle to be compared - /// Boolean - public bool Equals(Triangle? 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -207,13 +181,6 @@ namespace Org.OpenAPITools.Model /// public class TriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Triangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -226,9 +193,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader equilateralTriangleReader = reader; bool equilateralTriangleDeserialized = Client.ClientUtils.TryDeserialize(ref equilateralTriangleReader, options, out EquilateralTriangle? equilateralTriangle); @@ -238,15 +207,18 @@ namespace Org.OpenAPITools.Model Utf8JsonReader scaleneTriangleReader = reader; bool scaleneTriangleDeserialized = Client.ClientUtils.TryDeserialize(ref scaleneTriangleReader, options, out ScaleneTriangle? scaleneTriangle); - string? shapeType = default; - string? triangleType = default; + string shapeType = default; + string triangleType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string? propertyName = reader.GetString(); reader.Read(); @@ -259,6 +231,8 @@ namespace Org.OpenAPITools.Model case "triangleType": triangleType = reader.GetString(); break; + default: + break; } } } @@ -282,6 +256,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", triangle.ShapeType); + writer.WriteString("triangleType", triangle.TriangleType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs index f6d4c31c8c4..f8c40ffa61f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,17 +28,24 @@ namespace Org.OpenAPITools.Model /// /// TriangleInterface /// - public partial class TriangleInterface : IEquatable, IValidatableObject + public partial class TriangleInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// triangleType (required) + /// triangleType + [JsonConstructor] public TriangleInterface(string triangleType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (triangleType == null) throw new ArgumentNullException("triangleType is a required property for TriangleInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + TriangleType = triangleType; } @@ -53,7 +59,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,48 +74,6 @@ namespace Org.OpenAPITools.Model 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 TriangleInterface).AreEqual; - } - - /// - /// Returns true if TriangleInterface instances are equal - /// - /// Instance of TriangleInterface to be compared - /// Boolean - public bool Equals(TriangleInterface? 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; - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -121,4 +85,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type TriangleInterface + /// + public class TriangleInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override TriangleInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string triangleType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "triangleType": + triangleType = reader.GetString(); + break; + default: + break; + } + } + } + + return new TriangleInterface(triangleType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("triangleType", triangleInterface.TriangleType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs index 1cf4f172eca..f882dcb4c54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,101 +28,128 @@ namespace Org.OpenAPITools.Model /// /// User /// - public partial class User : IEquatable, IValidatableObject + public partial class User : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// id - /// username - /// firstName - /// lastName /// 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 - /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// 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. - public User(long? id = default, string? username = default, string? firstName = default, string? lastName = default, string? email = default, string? password = default, string? phone = default, int? userStatus = default, Object? objectWithNoDeclaredProps = default, Object? objectWithNoDeclaredPropsNullable = default, Object? anyTypeProp = default, Object? anyTypePropNullable = default) + /// 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) { - Id = id; - Username = username; - FirstName = firstName; - LastName = lastName; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for User and cannot be null."); + + if (username == null) + throw new ArgumentNullException("username is a required property for User and cannot be null."); + + if (firstName == null) + throw new ArgumentNullException("firstName is a required property for User and cannot be null."); + + if (lastName == null) + throw new ArgumentNullException("lastName is a required property for User and cannot be null."); + + if (email == null) + throw new ArgumentNullException("email is a required property for User and cannot be null."); + + if (password == null) + throw new ArgumentNullException("password is a required property for User and cannot be null."); + + if (phone == null) + throw new ArgumentNullException("phone is a required property for User and cannot be null."); + + if (userStatus == null) + throw new ArgumentNullException("userStatus is a required property for User and cannot be null."); + + if (objectWithNoDeclaredProps == null) + throw new ArgumentNullException("objectWithNoDeclaredProps is a required property for User and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Email = email; + FirstName = firstName; + Id = id; + LastName = lastName; + ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; Password = password; Phone = phone; UserStatus = userStatus; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + Username = username; AnyTypeProp = anyTypeProp; AnyTypePropNullable = anyTypePropNullable; + ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; } - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - public long? Id { get; set; } - - /// - /// Gets or Sets Username - /// - [JsonPropertyName("username")] - public string? Username { get; set; } - - /// - /// Gets or Sets FirstName - /// - [JsonPropertyName("firstName")] - public string? FirstName { get; set; } - - /// - /// Gets or Sets LastName - /// - [JsonPropertyName("lastName")] - public string? LastName { get; set; } - /// /// Gets or Sets Email /// [JsonPropertyName("email")] - public string? Email { get; set; } + public string Email { get; set; } /// - /// Gets or Sets Password + /// Gets or Sets FirstName /// - [JsonPropertyName("password")] - public string? Password { get; set; } + [JsonPropertyName("firstName")] + public string FirstName { get; set; } /// - /// Gets or Sets Phone + /// Gets or Sets Id /// - [JsonPropertyName("phone")] - public string? Phone { get; set; } + [JsonPropertyName("id")] + public long Id { get; set; } /// - /// User Status + /// Gets or Sets LastName /// - /// User Status - [JsonPropertyName("userStatus")] - public int? UserStatus { get; set; } + [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; } + public Object ObjectWithNoDeclaredProps { get; set; } /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// Gets or Sets Password /// - /// 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; } + [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 @@ -139,11 +165,18 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -153,102 +186,22 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" FirstName: ").Append(FirstName).Append("\n"); - sb.Append(" LastName: ").Append(LastName).Append("\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(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as User).AreEqual; - } - - /// - /// Returns true if User instances are equal - /// - /// Instance of User to be compared - /// Boolean - public bool Equals(User? 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) + this.Id.GetHashCode(); - if (this.Username != null) - { - hashCode = (hashCode * 59) + this.Username.GetHashCode(); - } - if (this.FirstName != null) - { - hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); - } - if (this.LastName != null) - { - hashCode = (hashCode * 59) + this.LastName.GetHashCode(); - } - if (this.Email != null) - { - hashCode = (hashCode * 59) + this.Email.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - if (this.Phone != null) - { - hashCode = (hashCode * 59) + this.Phone.GetHashCode(); - } - hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); - if (this.ObjectWithNoDeclaredProps != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); - } - if (this.ObjectWithNoDeclaredPropsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); - } - if (this.AnyTypeProp != null) - { - hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); - } - if (this.AnyTypePropNullable != null) - { - hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -260,4 +213,130 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type User + /// + public class UserJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override User Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "email": + email = reader.GetString(); + break; + case "firstName": + firstName = reader.GetString(); + break; + case "id": + id = reader.GetInt64(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "objectWithNoDeclaredProps": + objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref reader, options); + break; + case "password": + password = reader.GetString(); + break; + case "phone": + phone = reader.GetString(); + break; + case "userStatus": + userStatus = reader.GetInt32(); + break; + case "username": + username = reader.GetString(); + break; + case "anyTypeProp": + anyTypeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "anyTypePropNullable": + anyTypePropNullable = JsonSerializer.Deserialize(ref reader, options); + break; + case "objectWithNoDeclaredPropsNullable": + objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new User(email, firstName, id, lastName, objectWithNoDeclaredProps, password, phone, userStatus, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("email", user.Email); + writer.WriteString("firstName", user.FirstName); + writer.WriteNumber("id", (int)user.Id); + writer.WriteString("lastName", user.LastName); + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, options); + writer.WriteString("password", user.Password); + writer.WriteString("phone", user.Phone); + writer.WriteNumber("userStatus", (int)user.UserStatus); + writer.WriteString("username", user.Username); + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, options); + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, options); + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs index e8c73088da4..69d35becadf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,19 +28,32 @@ namespace Org.OpenAPITools.Model /// /// Whale /// - public partial class Whale : IEquatable, IValidatableObject + public partial class Whale : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// hasBaleen /// hasTeeth - public Whale(string className, bool? hasBaleen = default, bool? hasTeeth = default) + [JsonConstructor] + public Whale(string className, bool hasBaleen, bool hasTeeth) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (hasBaleen == null) + throw new ArgumentNullException("hasBaleen is a required property for Whale and cannot be null."); + + if (hasTeeth == null) + throw new ArgumentNullException("hasTeeth is a required property for Whale and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Whale and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; HasBaleen = hasBaleen; HasTeeth = hasTeeth; @@ -57,19 +69,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets HasBaleen /// [JsonPropertyName("hasBaleen")] - public bool? HasBaleen { get; set; } + public bool HasBaleen { get; set; } /// /// Gets or Sets HasTeeth /// [JsonPropertyName("hasTeeth")] - public bool? HasTeeth { get; set; } + public bool HasTeeth { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -86,50 +98,6 @@ namespace Org.OpenAPITools.Model 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 Whale).AreEqual; - } - - /// - /// Returns true if Whale instances are equal - /// - /// Instance of Whale to be compared - /// Boolean - public bool Equals(Whale? 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); - hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -141,4 +109,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Whale + /// + public class WhaleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Whale Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + bool hasBaleen = default; + bool hasTeeth = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "hasBaleen": + hasBaleen = reader.GetBoolean(); + break; + case "hasTeeth": + hasTeeth = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Whale(className, hasBaleen, hasTeeth); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", whale.ClassName); + writer.WriteBoolean("hasBaleen", whale.HasBaleen); + writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs index a43e56ab1d5..38792dce874 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -29,18 +28,28 @@ namespace Org.OpenAPITools.Model /// /// Zebra /// - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// type - public Zebra(string className, TypeEnum? type = default) : base() + [JsonConstructor] + public Zebra(string className, TypeEnum type) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (type == null) + throw new ArgumentNullException("type is a required property for Zebra and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Zebra and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Type = type; } @@ -53,28 +62,64 @@ namespace Org.OpenAPITools.Model /// /// Enum Plains for value: plains /// - [EnumMember(Value = "plains")] Plains = 1, /// /// Enum Mountain for value: mountain /// - [EnumMember(Value = "mountain")] Mountain = 2, /// /// Enum Grevys for value: grevys /// - [EnumMember(Value = "grevys")] Grevys = 3 } + /// + /// Returns a TypeEnum + /// + /// + /// + public static TypeEnum TypeEnumFromString(string value) + { + if (value == "plains") + return TypeEnum.Plains; + + if (value == "mountain") + return TypeEnum.Mountain; + + if (value == "grevys") + return TypeEnum.Grevys; + + throw new NotImplementedException($"Could not convert value to type TypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } + public TypeEnum Type { get; set; } /// /// Gets or Sets ClassName @@ -86,7 +131,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -103,49 +148,6 @@ namespace Org.OpenAPITools.Model 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 Zebra).AreEqual; - } - - /// - /// Returns true if Zebra instances are equal - /// - /// Instance of Zebra to be compared - /// Boolean - public bool Equals(Zebra? 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 = base.GetHashCode(); - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -157,4 +159,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Zebra + /// + public class ZebraJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Zebra Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + Zebra.TypeEnum type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "type": + string typeRawValue = reader.GetString(); + type = Zebra.TypeEnumFromString(typeRawValue); + break; + default: + break; + } + } + } + + return new Zebra(className, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", zebra.ClassName); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); + if (typeRawValue != null) + writer.WriteString("type", typeRawValue); + else + writer.WriteNull("type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 88fc1999394..96a7d12b515 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -22,9 +22,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md new file mode 100644 index 00000000000..6b76b0ef368 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md @@ -0,0 +1,260 @@ +# 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=Org.OpenAPITools', + '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 Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); + } + + 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 Org.OpenAPITools.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 +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 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: + + +### 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 + + +### bearer_test + + +- **Type**: Bearer Authentication + + +### http_basic_test + + +- **Type**: HTTP basic authentication + + +### http_signature_test + + + + +### 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 + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## 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: Org.OpenAPITools +- 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-netcore/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES index cf0f5c871be..65d841c450c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES @@ -92,31 +92,38 @@ docs/scripts/git_push.ps1 docs/scripts/git_push.sh src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md src/Org.OpenAPITools/Api/AnotherFakeApi.cs src/Org.OpenAPITools/Api/DefaultApi.cs src/Org.OpenAPITools/Api/FakeApi.cs src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +src/Org.OpenAPITools/Api/IApi.cs src/Org.OpenAPITools/Api/PetApi.cs src/Org.OpenAPITools/Api/StoreApi.cs src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs src/Org.OpenAPITools/Client/ApiKeyToken.cs src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/HostConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningToken.cs -src/Org.OpenAPITools/Client/IApi.cs src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs src/Org.OpenAPITools/Client/OAuthToken.cs -src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs src/Org.OpenAPITools/Client/RateLimitProvider`1.cs src/Org.OpenAPITools/Client/TokenBase.cs src/Org.OpenAPITools/Client/TokenContainer`1.cs src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs src/Org.OpenAPITools/Model/Activity.cs src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -197,3 +204,4 @@ src/Org.OpenAPITools/Model/User.cs src/Org.OpenAPITools/Model/Whale.cs src/Org.OpenAPITools/Model/Zebra.cs src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/README.md index 8a401855f49..f9c1c7f7462 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/README.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/README.md @@ -1,259 +1 @@ # Created with Openapi Generator - - -## Run the following powershell command to generate the library - -```ps1 -$properties = @( - 'apiName=Api', - 'targetFramework=net7.0', - 'validatable=true', - 'nullableReferenceTypes=false', - 'hideGenerationTimestamp=true', - 'packageVersion=1.0.0', - 'packageAuthors=OpenAPI', - 'packageCompany=OpenAPI', - 'packageCopyright=No Copyright', - 'packageDescription=A library generated from a OpenAPI doc', - 'packageName=Org.OpenAPITools', - '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 Org.OpenAPITools.Api; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Model; - -namespace YourProject -{ - public class Program - { - public static async Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); - var api = host.Services.GetRequiredService(); - ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); - } - - 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. - - -## 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 -- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later -- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.1 or later -- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.7.0 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: - - -### 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 - - -### bearer_test - - -- **Type**: Bearer Authentication - - -### http_basic_test - - -- **Type**: HTTP basic authentication - - -### http_signature_test - - - - -### 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 - -## Build -- SDK version: 1.0.0 -- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen - -## 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: false -- 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: Org.OpenAPITools -- 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-netcore/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md index f17e38282a0..b815f20b5a0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md @@ -631,7 +631,7 @@ No authorization required # **TestBodyWithQueryParams** -> void TestBodyWithQueryParams (string query, User user) +> void TestBodyWithQueryParams (User user, string query) @@ -652,12 +652,12 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new FakeApi(config); - var query = "query_example"; // string | var user = new User(); // User | + var query = "query_example"; // string | try { - apiInstance.TestBodyWithQueryParams(query, user); + apiInstance.TestBodyWithQueryParams(user, query); } catch (ApiException e) { @@ -676,7 +676,7 @@ This returns an ApiResponse object which contains the response data, status code ```csharp try { - apiInstance.TestBodyWithQueryParamsWithHttpInfo(query, user); + apiInstance.TestBodyWithQueryParamsWithHttpInfo(user, query); } catch (ApiException e) { @@ -690,8 +690,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **query** | **string** | | | | **user** | [**User**](User.md) | | | +| **query** | **string** | | | ### Return type @@ -807,7 +807,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null) +> void TestEndpointParameters (byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -834,17 +834,17 @@ namespace Example config.Password = "YOUR_PASSWORD"; var apiInstance = new FakeApi(config); + var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | None var number = 8.14D; // decimal | None var _double = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | 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 _float = 3.4F; // float? | None (optional) var integer = 56; // int? | None (optional) var int32 = 56; // int? | None (optional) var int64 = 789L; // long? | None (optional) - var _float = 3.4F; // float? | None (optional) var _string = "_string_example"; // string | None (optional) - var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) - var date = DateTime.Parse("2013-10-20"); // DateTime? | 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") @@ -852,7 +852,7 @@ namespace Example try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -872,7 +872,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParametersWithHttpInfo(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -886,17 +886,17 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| +| **_byte** | **byte[]** | None | | | **number** | **decimal** | None | | | **_double** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **_byte** | **byte[]** | None | | +| **date** | **DateTime?** | None | [optional] | +| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | +| **_float** | **float?** | None | [optional] | | **integer** | **int?** | None | [optional] | | **int32** | **int?** | None | [optional] | | **int64** | **long?** | None | [optional] | -| **_float** | **float?** | None | [optional] | | **_string** | **string** | None | [optional] | -| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | -| **date** | **DateTime?** | None | [optional] | | **password** | **string** | None | [optional] | | **callback** | **string** | None | [optional] | | **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | @@ -925,7 +925,7 @@ void (empty response body) # **TestEnumParameters** -> void TestEnumParameters (List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null) +> 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 @@ -950,17 +950,17 @@ namespace Example 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 enumQueryInteger = 1; // int? | Query parameter enum test (double) (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 enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) (default to $) var enumFormString = "_abc"; // string | Form parameter enum test (string) (optional) (default to -efg) try { // To test enum parameters - apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -980,7 +980,7 @@ This returns an ApiResponse object which contains the response data, status code try { // To test enum parameters - apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -996,11 +996,11 @@ catch (ApiException e) |------|------|-------------|-------| | **enumHeaderStringArray** | [**List<string>**](string.md) | Header parameter enum test (string array) | [optional] | | **enumQueryStringArray** | [**List<string>**](string.md) | Query parameter enum test (string array) | [optional] | -| **enumQueryInteger** | **int?** | Query parameter enum test (double) | [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] | -| **enumFormStringArray** | [**List<string>**](string.md) | Form parameter enum test (string array) | [optional] [default to $] | | **enumFormString** | **string** | Form parameter enum test (string) | [optional] [default to -efg] | ### Return type @@ -1027,7 +1027,7 @@ No authorization required # **TestGroupParameters** -> void TestGroupParameters (int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null) +> void TestGroupParameters (bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null) Fake endpoint to test group parameters (optional) @@ -1053,17 +1053,17 @@ namespace Example config.AccessToken = "YOUR_BEARER_TOKEN"; var apiInstance = new FakeApi(config); - var requiredStringGroup = 56; // int | Required String in group parameters 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 stringGroup = 56; // int? | String in group parameters (optional) 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(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1083,7 +1083,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint to test group parameters (optional) - apiInstance.TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParametersWithHttpInfo(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1097,11 +1097,11 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | +| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredInt64Group** | **long** | Required Integer in group parameters | | -| **stringGroup** | **int?** | String in group parameters | [optional] | | **booleanGroup** | **bool?** | Boolean in group parameters | [optional] | +| **stringGroup** | **int?** | String in group parameters | [optional] | | **int64Group** | **long?** | Integer in group parameters | [optional] | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md index 8ece47af9ca..da6486e4cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md @@ -664,7 +664,7 @@ void (empty response body) # **UploadFile** -> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) +> ApiResponse UploadFile (long petId, System.IO.Stream file = null, string additionalMetadata = null) uploads an image @@ -689,13 +689,13 @@ namespace Example var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to update - var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) 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, additionalMetadata, file); + ApiResponse result = apiInstance.UploadFile(petId, file, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -716,7 +716,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image - ApiResponse response = apiInstance.UploadFileWithHttpInfo(petId, additionalMetadata, file); + 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); @@ -734,8 +734,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| | **petId** | **long** | ID of pet to update | | -| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | | **file** | **System.IO.Stream****System.IO.Stream** | file to upload | [optional] | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | ### Return type @@ -760,7 +760,7 @@ catch (ApiException e) # **UploadFileWithRequiredFile** -> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) +> ApiResponse UploadFileWithRequiredFile (System.IO.Stream requiredFile, long petId, string additionalMetadata = null) uploads an image (required) @@ -784,14 +784,14 @@ namespace Example config.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(config); - var petId = 789L; // long | ID of pet to update 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(petId, requiredFile, additionalMetadata); + ApiResponse result = apiInstance.UploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -812,7 +812,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image (required) - ApiResponse response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + 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); @@ -829,8 +829,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **petId** | **long** | ID of pet to update | | | **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 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md index fd1c1a7d62b..a862c8c112a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md @@ -623,7 +623,7 @@ No authorization required # **UpdateUser** -> void UpdateUser (string username, User user) +> void UpdateUser (User user, string username) Updated user @@ -646,13 +646,13 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new UserApi(config); - var username = "username_example"; // string | name that need to be deleted var user = new User(); // User | Updated user object + var username = "username_example"; // string | name that need to be deleted try { // Updated user - apiInstance.UpdateUser(username, user); + apiInstance.UpdateUser(user, username); } catch (ApiException e) { @@ -672,7 +672,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Updated user - apiInstance.UpdateUserWithHttpInfo(username, user); + apiInstance.UpdateUserWithHttpInfo(user, username); } catch (ApiException e) { @@ -686,8 +686,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **username** | **string** | name that need to be deleted | | | **user** | [**User**](User.md) | Updated user object | | +| **username** | **string** | name that need to be deleted | | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md index 1f919450009..f79869f95a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md @@ -4,14 +4,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapProperty** | **Dictionary<string, string>** | | [optional] +**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] -**Anytype1** | **Object** | | [optional] +**MapProperty** | **Dictionary<string, string>** | | [optional] **MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] -**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/ApiResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ApiResponse.md index bc808ceeae3..d89ed1a25dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ApiResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ApiResponse.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | **int** | | [optional] -**Type** | **string** | | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/ArrayTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ArrayTest.md index 32365e6d4d0..ed572120cd6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ArrayTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ArrayTest.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayOfString** | **List<string>** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Capitalization.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Capitalization.md index fde98a967ef..9e225c17232 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Capitalization.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Capitalization.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SmallCamel** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [optional] **CapitalCamel** | **string** | | [optional] -**SmallSnake** | **string** | | [optional] **CapitalSnake** | **string** | | [optional] **SCAETHFlowPoints** | **string** | | [optional] -**ATT_NAME** | **string** | Name of the pet | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Category.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Category.md index c2cf3f8e919..6eb0a2e13ea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Category.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Category.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Name** | **string** | | [default to "default-name"] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/ClassModel.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ClassModel.md index bb35816c914..a098828a04f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ClassModel.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ClassModel.md @@ -5,7 +5,7 @@ Model for testing model with \"_class\" property Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Class** | **string** | | [optional] +**ClassProperty** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md index 18117e6c938..fcee9662afb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md @@ -6,8 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] -**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **Shapes** | [**List<Shape>**](Shape.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.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-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md index 2a27962cc52..7467f67978c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**JustSymbol** | **string** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md index 71602270bab..53bbfe31e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**EnumStringRequired** | **string** | | -**EnumString** | **string** | | [optional] **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] -**OuterEnumInteger** | **OuterEnumInteger** | | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/FooGetDefaultResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FooGetDefaultResponse.md index 47e50daca3e..78c99facf59 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FooGetDefaultResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FooGetDefaultResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] +**StringProperty** | [**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-netcore/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md index 0b92c2fb10a..4e34a6d18b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md @@ -4,22 +4,22 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Number** | **decimal** | | -**Byte** | **byte[]** | | +**Binary** | **System.IO.Stream** | | [optional] +**ByteProperty** | **byte[]** | | **Date** | **DateTime** | | -**Password** | **string** | | -**Integer** | **int** | | [optional] +**DateTime** | **DateTime** | | [optional] +**DecimalProperty** | **decimal** | | [optional] +**DoubleProperty** | **double** | | [optional] +**FloatProperty** | **float** | | [optional] **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] -**Float** | **float** | | [optional] -**Double** | **double** | | [optional] -**Decimal** | **decimal** | | [optional] -**String** | **string** | | [optional] -**Binary** | **System.IO.Stream** | | [optional] -**DateTime** | **DateTime** | | [optional] -**Uuid** | **Guid** | | [optional] +**Integer** | **int** | | [optional] +**Number** | **decimal** | | +**Password** | **string** | | **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] +**StringProperty** | **string** | | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md index aaee09f7870..5dd27228bb0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md index 031d2b96065..0bac85a8e83 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **Guid** | | [optional] **DateTime** | **DateTime** | | [optional] **Map** | [**Dictionary<string, Animal>**](Animal.md) | | [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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Model200Response.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Model200Response.md index 8bc8049f46f..93139e1d1aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Model200Response.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Model200Response.md @@ -5,8 +5,8 @@ Model for testing model name starting with number Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**ClassProperty** | **string** | | [optional] **Name** | **int** | | [optional] -**Class** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/ModelClient.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ModelClient.md index 9e0e83645f3..51cf0636e72 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ModelClient.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ModelClient.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_Client** | **string** | | [optional] +**_ClientProperty** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Name.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Name.md index 2ee782c0c54..11f49b9fd40 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Name.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Name.md @@ -6,8 +6,8 @@ Model for testing model name same as property name Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **NameProperty** | **int** | | -**SnakeCase** | **int** | | [optional] [readonly] **Property** | **string** | | [optional] +**SnakeCase** | **int** | | [optional] [readonly] **_123Number** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md index d4a19d1856b..ac86336ea70 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**IntegerProp** | **int?** | | [optional] -**NumberProp** | **decimal?** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool?** | | [optional] -**StringProp** | **string** | | [optional] **DateProp** | **DateTime?** | | [optional] **DatetimeProp** | **DateTime?** | | [optional] -**ArrayNullableProp** | **List<Object>** | | [optional] -**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**IntegerProp** | **int?** | | [optional] +**NumberProp** | **decimal?** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] -**ObjectItemsNullable** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/ObjectWithDeprecatedFields.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ObjectWithDeprecatedFields.md index b737f7d757a..9f44c24d19a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ObjectWithDeprecatedFields.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/ObjectWithDeprecatedFields.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **string** | | [optional] -**Id** | **decimal** | | [optional] -**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/OuterComposite.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/OuterComposite.md index abf676810fb..8985c59d094 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/OuterComposite.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/OuterComposite.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**MyBoolean** | **bool** | | [optional] **MyNumber** | **decimal** | | [optional] **MyString** | **string** | | [optional] -**MyBoolean** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/Pet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Pet.md index 7de10304abf..b13bb576b45 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Pet.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/Pet.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | -**Id** | **long** | | [optional] -**Category** | [**Category**](Category.md) | | [optional] -**Tags** | [**List<Tag>**](Tag.md) | | [optional] **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/SpecialModelName.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/SpecialModelName.md index 662fa6f4a38..b48f3490005 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/SpecialModelName.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/SpecialModelName.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SpecialPropertyName** | **long** | | [optional] **SpecialModelNameProperty** | **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-netcore/OpenAPIClient-generichost-net6.0/docs/models/User.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/User.md index a0f0d223899..455f031674d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/User.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Username** | **string** | | [optional] -**FirstName** | **string** | | [optional] -**LastName** | **string** | | [optional] **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] -**ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs index fea7e39428f..30f54c0aab5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class AnotherFakeApiTests : ApiTestsBase { - private readonly IAnotherFakeApi _instance; + private readonly IApi.IAnotherFakeApi _instance; public AnotherFakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index 88d6fc1f488..75e37de2412 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Extensions.Hosting; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; /* ********************************************************************************* @@ -49,7 +50,7 @@ namespace Org.OpenAPITools.Test.Api } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureApi((context, options) => + .ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration[""], timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 16f60704f2a..d79076dcd63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class DefaultApiTests : ApiTestsBase { - private readonly IDefaultApi _instance; + private readonly IApi.IDefaultApi _instance; public DefaultApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 4eee3d2b6eb..256df5697c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -13,7 +13,8 @@ using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Security.Cryptography; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; using Xunit; namespace Org.OpenAPITools.Test.Api @@ -24,7 +25,7 @@ namespace Org.OpenAPITools.Test.Api public class DependencyInjectionTest { private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -45,7 +46,7 @@ namespace Org.OpenAPITools.Test.Api .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -121,25 +122,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -149,25 +150,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -177,25 +178,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithAClientTest() { - var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -205,25 +206,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index b70f2a8adc7..4c965120e69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeApiTests : ApiTestsBase { - private readonly IFakeApi _instance; + private readonly IApi.IFakeApi _instance; public FakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -131,9 +131,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestBodyWithQueryParamsAsyncTest() { - string query = default; User user = default; - await _instance.TestBodyWithQueryParamsAsync(query, user); + string query = default; + await _instance.TestBodyWithQueryParamsAsync(user, query); } /// @@ -153,21 +153,21 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestEndpointParametersAsyncTest() { + byte[] _byte = default; decimal number = default; double _double = default; string patternWithoutDelimiter = default; - byte[] _byte = default; + DateTime? date = default; + System.IO.Stream binary = default; + float? _float = default; int? integer = default; int? int32 = default; long? int64 = default; - float? _float = default; string _string = default; - System.IO.Stream binary = default; - DateTime? date = default; string password = default; string callback = default; DateTime? dateTime = default; - await _instance.TestEndpointParametersAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + await _instance.TestEndpointParametersAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } /// @@ -178,13 +178,13 @@ namespace Org.OpenAPITools.Test.Api { List enumHeaderStringArray = default; List enumQueryStringArray = default; - int? enumQueryInteger = default; double? enumQueryDouble = default; + int? enumQueryInteger = default; + List enumFormStringArray = default; string enumHeaderString = default; string enumQueryString = default; - List enumFormStringArray = default; string enumFormString = default; - await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } /// @@ -193,13 +193,13 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestGroupParametersAsyncTest() { - int requiredStringGroup = default; bool requiredBooleanGroup = default; + int requiredStringGroup = default; long requiredInt64Group = default; - int? stringGroup = default; bool? booleanGroup = default; + int? stringGroup = default; long? int64Group = default; - await _instance.TestGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + await _instance.TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs index 0e8d44fe985..5a34bf585f0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeClassnameTags123ApiTests : ApiTestsBase { - private readonly IFakeClassnameTags123Api _instance; + private readonly IApi.IFakeClassnameTags123Api _instance; public FakeClassnameTags123ApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index 92922eda1b7..8ebf3b80bf4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class PetApiTests : ApiTestsBase { - private readonly IPetApi _instance; + private readonly IApi.IPetApi _instance; public PetApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -134,9 +134,9 @@ namespace Org.OpenAPITools.Test.Api public async Task UploadFileAsyncTest() { long petId = default; - string additionalMetadata = default; System.IO.Stream file = default; - var response = await _instance.UploadFileAsync(petId, additionalMetadata, file); + string additionalMetadata = default; + var response = await _instance.UploadFileAsync(petId, file, additionalMetadata); Assert.IsType(response); } @@ -146,10 +146,10 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UploadFileWithRequiredFileAsyncTest() { - long petId = default; System.IO.Stream requiredFile = default; + long petId = default; string additionalMetadata = default; - var response = await _instance.UploadFileWithRequiredFileAsync(petId, requiredFile, additionalMetadata); + var response = await _instance.UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata); Assert.IsType(response); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index 98748893e32..679d6488380 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class StoreApiTests : ApiTestsBase { - private readonly IStoreApi _instance; + private readonly IApi.IStoreApi _instance; public StoreApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index 0df256733af..b8006066faf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class UserApiTests : ApiTestsBase { - private readonly IUserApi _instance; + private readonly IApi.IUserApi _instance; public UserApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -129,9 +129,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UpdateUserAsyncTest() { - string username = default; User user = default; - await _instance.UpdateUserAsync(username, user); + string username = default; + await _instance.UpdateUserAsync(user, username); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs index f211a64884a..174a7e333af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs index afe9e846ee9..c7479a3c343 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index 9ab029ed097..95bd1593503 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'MapProperty' + /// Test the property 'EmptyMap' /// [Fact] - public void MapPropertyTest() + public void EmptyMapTest() { - // TODO unit test for the property 'MapProperty' + // TODO unit test for the property 'EmptyMap' } /// /// Test the property 'MapOfMapProperty' @@ -73,12 +72,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapOfMapProperty' } /// - /// Test the property 'Anytype1' + /// Test the property 'MapProperty' /// [Fact] - public void Anytype1Test() + public void MapPropertyTest() { - // TODO unit test for the property 'Anytype1' + // TODO unit test for the property 'MapProperty' } /// /// Test the property 'MapWithUndeclaredPropertiesAnytype1' @@ -105,14 +104,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' } /// - /// Test the property 'EmptyMap' - /// - [Fact] - public void EmptyMapTest() - { - // TODO unit test for the property 'EmptyMap' - } - /// /// Test the property 'MapWithUndeclaredPropertiesString' /// [Fact] @@ -120,6 +111,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index ced34a4faad..8c38ac47af7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 2a2e098e608..a2a9a2d49de 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Code' } /// - /// Test the property 'Type' - /// - [Fact] - public void TypeTest() - { - // TODO unit test for the property 'Type' - } - /// /// Test the property 'Message' /// [Fact] @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs index f945f659368..0610780d65d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs index 468d60184ad..e0bd59e7732 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs index 0b259d7d391..8f046a0bf6b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs index 27f312ad25f..53b2fe30fdb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs index a433e8c87cf..df87ba3aaaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'ArrayOfString' - /// - [Fact] - public void ArrayOfStringTest() - { - // TODO unit test for the property 'ArrayOfString' - } /// /// Test the property 'ArrayArrayOfInteger' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs index 8a6eeb82eee..6f31ba2029b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs index 8d8cc376b03..6cb6c62ffd0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs index 3cdccaa7595..9798a17577b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs index 185c83666fc..b84c7c85a7d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'SmallCamel' + /// Test the property 'ATT_NAME' /// [Fact] - public void SmallCamelTest() + public void ATT_NAMETest() { - // TODO unit test for the property 'SmallCamel' + // TODO unit test for the property 'ATT_NAME' } /// /// Test the property 'CapitalCamel' @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'CapitalCamel' } /// - /// Test the property 'SmallSnake' - /// - [Fact] - public void SmallSnakeTest() - { - // TODO unit test for the property 'SmallSnake' - } - /// /// Test the property 'CapitalSnake' /// [Fact] @@ -97,12 +88,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'SCAETHFlowPoints' } /// - /// Test the property 'ATT_NAME' + /// Test the property 'SmallCamel' /// [Fact] - public void ATT_NAMETest() + public void SmallCamelTest() { - // TODO unit test for the property 'ATT_NAME' + // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs index fb51c28489c..3498bb0c152 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatTests.cs index 9c3c48ffefe..402a476d079 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index 621877aa973..822f8241fa0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } /// /// Test the property 'Id' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs index 49a53932490..d4de4c47417 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs index 0fe3ebfa06e..f1b0aa1005c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs index d29472e83aa..2e6c120d8fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Class' + /// Test the property 'ClassProperty' /// [Fact] - public void ClassTest() + public void ClassPropertyTest() { - // TODO unit test for the property 'Class' + // TODO unit test for the property 'ClassProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs index 6c50fe7aab5..3f2f96e73a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs index 572d9bffa79..087d38674bb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs index 1da5f4011c9..85ecbfdda55 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs index b22a4442096..1e86d761507 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogTests.cs index bf906f01bc6..ef2eabfca31 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0709ad9eeb3..c38867cb5ae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ShapeOrNull' } /// - /// Test the property 'NullableShape' - /// - [Fact] - public void NullableShapeTest() - { - // TODO unit test for the property 'NullableShape' - } - /// /// Test the property 'Shapes' /// [Fact] @@ -88,6 +79,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Shapes' } + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs index 5779ca29477..ee3d000f32f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'JustSymbol' - /// - [Fact] - public void JustSymbolTest() - { - // TODO unit test for the property 'JustSymbol' - } /// /// Test the property 'ArrayEnum' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs index a17738c5cbc..e2fc2d02282 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index a22c39ca845..60e3aca92bd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'EnumStringRequired' - /// - [Fact] - public void EnumStringRequiredTest() - { - // TODO unit test for the property 'EnumStringRequired' - } - /// - /// Test the property 'EnumString' - /// - [Fact] - public void EnumStringTest() - { - // TODO unit test for the property 'EnumString' - } /// /// Test the property 'EnumInteger' /// @@ -97,20 +80,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumNumber' } /// - /// Test the property 'OuterEnum' + /// Test the property 'EnumString' /// [Fact] - public void OuterEnumTest() + public void EnumStringTest() { - // TODO unit test for the property 'OuterEnum' + // TODO unit test for the property 'EnumString' } /// - /// Test the property 'OuterEnumInteger' + /// Test the property 'EnumStringRequired' /// [Fact] - public void OuterEnumIntegerTest() + public void EnumStringRequiredTest() { - // TODO unit test for the property 'OuterEnumInteger' + // TODO unit test for the property 'EnumStringRequired' } /// /// Test the property 'OuterEnumDefaultValue' @@ -121,6 +104,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -128,6 +119,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs index 9ca755c4b07..9ab78a59779 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs index 9f45b4fe89d..9836a779bf0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileTests.cs index 761bb72a844..4f0e7079bc8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs index 0154d528418..b7313941a69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'String' + /// Test the property 'StringProperty' /// [Fact] - public void StringTest() + public void StringPropertyTest() { - // TODO unit test for the property 'String' + // TODO unit test for the property 'StringProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooTests.cs index 0b6ed52edbd..c0bdf85f9b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index 707847bbcd1..d3a978bdc4c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,20 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Number' + /// Test the property 'Binary' /// [Fact] - public void NumberTest() + public void BinaryTest() { - // TODO unit test for the property 'Number' + // TODO unit test for the property 'Binary' } /// - /// Test the property 'Byte' + /// Test the property 'ByteProperty' /// [Fact] - public void ByteTest() + public void BytePropertyTest() { - // TODO unit test for the property 'Byte' + // TODO unit test for the property 'ByteProperty' } /// /// Test the property 'Date' @@ -81,20 +80,36 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Date' } /// - /// Test the property 'Password' + /// Test the property 'DateTime' /// [Fact] - public void PasswordTest() + public void DateTimeTest() { - // TODO unit test for the property 'Password' + // TODO unit test for the property 'DateTime' } /// - /// Test the property 'Integer' + /// Test the property 'DecimalProperty' /// [Fact] - public void IntegerTest() + public void DecimalPropertyTest() { - // TODO unit test for the property 'Integer' + // TODO unit test for the property 'DecimalProperty' + } + /// + /// Test the property 'DoubleProperty' + /// + [Fact] + public void DoublePropertyTest() + { + // TODO unit test for the property 'DoubleProperty' + } + /// + /// Test the property 'FloatProperty' + /// + [Fact] + public void FloatPropertyTest() + { + // TODO unit test for the property 'FloatProperty' } /// /// Test the property 'Int32' @@ -113,60 +128,28 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Int64' } /// - /// Test the property 'Float' + /// Test the property 'Integer' /// [Fact] - public void FloatTest() + public void IntegerTest() { - // TODO unit test for the property 'Float' + // TODO unit test for the property 'Integer' } /// - /// Test the property 'Double' + /// Test the property 'Number' /// [Fact] - public void DoubleTest() + public void NumberTest() { - // TODO unit test for the property 'Double' + // TODO unit test for the property 'Number' } /// - /// Test the property 'Decimal' + /// Test the property 'Password' /// [Fact] - public void DecimalTest() + public void PasswordTest() { - // TODO unit test for the property 'Decimal' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' + // TODO unit test for the property 'Password' } /// /// Test the property 'PatternWithDigits' @@ -184,6 +167,22 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'PatternWithDigitsAndDelimiter' } + /// + /// Test the property 'StringProperty' + /// + [Fact] + public void StringPropertyTest() + { + // TODO unit test for the property 'StringProperty' + } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs index 3a0b55b93e3..3ef884e59c6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs index ddc424d56ea..9ab6b7f2781 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs index cbd35f9173c..036c5641cf4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index faa4930944b..182cf7350b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs index 651a9f0ce30..d9a07efcf9a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs index 857190a3334..d29edf5dd10 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs index 8e0dae93420..2fed6f0b4cc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ListTests.cs index 2ed828d0520..398a4644921 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ListTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs index 6477ab950fa..0889d80a708 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs index 20036e1c905..0dc95aa6b23 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// 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' - } /// /// Test the property 'DirectMap' /// @@ -88,6 +71,22 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index f56cd715f45..d94f882e0a2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' - } /// /// Test the property 'DateTime' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Map' } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs index e25478618f2..31f2a754314 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'ClassProperty' + /// + [Fact] + public void ClassPropertyTest() + { + // TODO unit test for the property 'ClassProperty' + } /// /// Test the property 'Name' /// @@ -64,14 +71,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Name' } - /// - /// Test the property 'Class' - /// - [Fact] - public void ClassTest() - { - // TODO unit test for the property 'Class' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 24a9e263158..40b3700ce95 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '_Client' + /// Test the property '_ClientProperty' /// [Fact] - public void _ClientTest() + public void _ClientPropertyTest() { - // TODO unit test for the property '_Client' + // TODO unit test for the property '_ClientProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NameTests.cs index 61f8ad11379..523b3e050aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'NameProperty' } /// - /// Test the property 'SnakeCase' - /// - [Fact] - public void SnakeCaseTest() - { - // TODO unit test for the property 'SnakeCase' - } - /// /// Test the property 'Property' /// [Fact] @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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 '_123Number' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 8f00505612a..adf7c14f131 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,36 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'IntegerProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void IntegerPropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'IntegerProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// - /// Test the property 'NumberProp' + /// Test the property 'ObjectItemsNullable' /// [Fact] - public void NumberPropTest() + public void ObjectItemsNullableTest() { - // TODO unit test for the property 'NumberProp' + // 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' @@ -81,14 +96,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'BooleanProp' } /// - /// Test the property 'StringProp' - /// - [Fact] - public void StringPropTest() - { - // TODO unit test for the property 'StringProp' - } - /// /// Test the property 'DateProp' /// [Fact] @@ -105,36 +112,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DatetimeProp' } /// - /// Test the property 'ArrayNullableProp' + /// Test the property 'IntegerProp' /// [Fact] - public void ArrayNullablePropTest() + public void IntegerPropTest() { - // TODO unit test for the property 'ArrayNullableProp' + // TODO unit test for the property 'IntegerProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'NumberProp' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void NumberPropTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' - } - /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - /// - /// Test the property 'ObjectNullableProp' - /// - [Fact] - public void ObjectNullablePropTest() - { - // TODO unit test for the property 'ObjectNullableProp' + // TODO unit test for the property 'NumberProp' } /// /// Test the property 'ObjectAndItemsNullableProp' @@ -145,12 +136,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ObjectAndItemsNullableProp' } /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ObjectNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ObjectNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs index 8202ef63914..734d03e5e7a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs index 3a06cb020b2..5db923c1d3f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs index 82f93fab48c..9e9b651f818 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Uuid' + /// Test the property 'Bars' /// [Fact] - public void UuidTest() + public void BarsTest() { - // TODO unit test for the property 'Uuid' - } - /// - /// Test the property 'Id' - /// - [Fact] - public void IdTest() - { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'Bars' } /// /// Test the property 'DeprecatedRef' @@ -81,12 +72,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DeprecatedRef' } /// - /// Test the property 'Bars' + /// Test the property 'Id' /// [Fact] - public void BarsTest() + public void IdTest() { - // TODO unit test for the property 'Bars' + // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs index cf5c561c547..10682e72f21 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs index 2efda0db59c..8c176d9f94c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } /// /// Test the property 'MyNumber' /// @@ -72,14 +79,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'MyString' } - /// - /// Test the property 'MyBoolean' - /// - [Fact] - public void MyBooleanTest() - { - // TODO unit test for the property 'MyBoolean' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs index 986fff774c4..9f6d8b52b6c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs index 015d5dab945..e51365edb27 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs index 385e899110a..36e6a060f97 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs index f47304767b9..b38c693d1a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs index 1e17568ed33..34cae43eac1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs index 28ea4d8478d..66cfbf7bdb5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,22 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// 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' /// @@ -73,20 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Id' + /// Test the property 'Status' /// [Fact] - public void IdTest() + public void StatusTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Category' - /// - [Fact] - public void CategoryTest() - { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Status' } /// /// Test the property 'Tags' @@ -96,14 +103,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Tags' } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PigTests.cs index a66befe8f58..0e85eabf160 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs index eff3c6ddc9b..98aad34f4b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs index 6eef9f4c816..42243bd29c0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs index 3d62673d093..e15b2c5c749 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs index dc3d0fad54c..7e99972f26e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs index 65fa199fe35..9969564490d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs index 018dffb5964..cad95d2963c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs index 7bd0bc86f96..3129f3775c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs index ef564357648..a33da20eda6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs index 783a9657ed4..b2d995af504 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs index 3bcd65e792d..0221971c076 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 91682a7afd6..1a5bb10af80 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'SpecialPropertyName' - /// - [Fact] - public void SpecialPropertyNameTest() - { - // TODO unit test for the property 'SpecialPropertyName' - } /// /// Test the property 'SpecialModelNameProperty' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialModelNameProperty' } + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TagTests.cs index 6d56232d0a7..92a5f823659 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs index fba65470bee..924d6b42d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs index bdaab0b4796..9701da6a541 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs index a7b095e4c28..a464c80c84c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Id' + /// Test the property 'Email' /// [Fact] - public void IdTest() + public void EmailTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Username' - /// - [Fact] - public void UsernameTest() - { - // TODO unit test for the property 'Username' + // TODO unit test for the property 'Email' } /// /// Test the property 'FirstName' @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -89,12 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'LastName' } /// - /// Test the property 'Email' + /// Test the property 'ObjectWithNoDeclaredProps' /// [Fact] - public void EmailTest() + public void ObjectWithNoDeclaredPropsTest() { - // TODO unit test for the property 'Email' + // TODO unit test for the property 'ObjectWithNoDeclaredProps' } /// /// Test the property 'Password' @@ -121,20 +120,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'UserStatus' } /// - /// Test the property 'ObjectWithNoDeclaredProps' + /// Test the property 'Username' /// [Fact] - public void ObjectWithNoDeclaredPropsTest() + public void UsernameTest() { - // TODO unit test for the property 'ObjectWithNoDeclaredProps' - } - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + // TODO unit test for the property 'Username' } /// /// Test the property 'AnyTypeProp' @@ -152,6 +143,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs index 9b82c29c8fd..91a7b21f213 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs index 39e0561fe0f..08b1c6056c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 8d17c12883d..4611b7d5ecf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,13 +8,12 @@ - + - + - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 428a326e69e..7bca5fd0e17 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IAnotherFakeApi : IApi { @@ -48,21 +49,19 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); } + Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class AnotherFakeApi : IAnotherFakeApi + public partial class AnotherFakeApi : IApi.IAnotherFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -119,6 +118,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -159,6 +167,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnCall123TestSpecialTags(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCall123TestSpecialTags(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCall123TestSpecialTags(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -168,18 +216,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnCall123TestSpecialTags(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -189,6 +233,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -198,7 +244,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -208,31 +254,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCall123TestSpecialTags(apiResponse, modelClient); + } return apiResponse; } @@ -240,8 +279,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCall123TestSpecialTags(e, "/another-fake/dummy", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/DefaultApi.cs index 78cd5681661..708148c438b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IDefaultApi : IApi { @@ -46,21 +47,19 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<FooGetDefaultResponse> - Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); } + Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class DefaultApi : IDefaultApi + public partial class DefaultApi : IApi.IDefaultApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -117,6 +116,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// /// @@ -155,6 +163,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFooGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFooGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFooGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// @@ -163,16 +199,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FooGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFooGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/foo"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -183,31 +224,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFooGet(apiResponse); + } return apiResponse; } @@ -215,8 +249,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFooGet(e, "/foo", uriBuilder.Path); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs index 0f8c448ecd7..0c0b289c532 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeApi : IApi { @@ -47,6 +48,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<HealthCheckResult> Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -70,6 +72,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<bool> Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -93,6 +96,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<OuterComposite> Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -116,6 +120,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<decimal> Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -139,6 +144,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> Task FakeOuterStringSerializeAsync(string body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// Array of Enums /// @@ -160,6 +166,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<OuterEnum>> Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -183,18 +190,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null); - /// - /// - /// - /// - /// - /// - /// Thrown when fails to make API call - /// - /// - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -203,11 +198,25 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); + Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); + /// /// To test \"client\" model /// @@ -231,30 +240,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = 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. - /// Task<ApiResponse<object>> - Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -263,41 +248,48 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// 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> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = 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) - /// Header parameter enum test (string) (optional, default to -efg) - /// Query parameter enum test (string) (optional, default to -efg) - /// Form parameter enum test (string array) (optional, default to $) - /// Form parameter enum test (string) (optional, default to -efg) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// To test enum parameters @@ -308,31 +300,34 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// Fake endpoint to test group parameters (optional) - /// - /// - /// Fake endpoint to test group parameters (optional) - /// - /// Thrown when fails to make API call - /// Required String in group parameters - /// Required Boolean in group parameters - /// Required Integer in group parameters - /// String in group parameters (optional) - /// Boolean in group parameters (optional) - /// Integer in group parameters (optional) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint to test group parameters (optional) @@ -341,15 +336,33 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// test inline additionalProperties /// @@ -373,6 +386,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null); + /// /// test json serialization of form data /// @@ -398,6 +412,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -428,21 +443,19 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); } + Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeApi : IFakeApi + public partial class FakeApi : IApi.IFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -499,6 +512,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Health check endpoint /// @@ -537,6 +559,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFakeHealthGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFakeHealthGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFakeHealthGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Health check endpoint /// @@ -545,16 +595,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeHealthGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFakeHealthGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/health"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -565,31 +620,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeHealthGet(apiResponse); + } return apiResponse; } @@ -597,7 +645,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeHealthGet(e, "/fake/health", uriBuilder.Path); throw; } } @@ -621,6 +669,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual bool? OnFakeOuterBooleanSerialize(bool? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterBooleanSerialize(ApiResponse apiResponse, bool? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterBooleanSerialize(Exception exception, string pathFormat, string path, bool? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer boolean types /// @@ -630,11 +709,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterBooleanSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -644,6 +726,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -653,7 +737,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -663,31 +747,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterBooleanSerialize(apiResponse, body); + } return apiResponse; } @@ -695,7 +772,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterBooleanSerialize(e, "/fake/outer/boolean", uriBuilder.Path, body); throw; } } @@ -740,6 +817,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual OuterComposite OnFakeOuterCompositeSerialize(OuterComposite outerComposite) + { + return outerComposite; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterCompositeSerialize(ApiResponse apiResponse, OuterComposite outerComposite) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterCompositeSerialize(Exception exception, string pathFormat, string path, OuterComposite outerComposite) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of object with outer number type /// @@ -749,11 +857,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + outerComposite = OnFakeOuterCompositeSerialize(outerComposite); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -763,6 +874,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(outerComposite, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -772,7 +885,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -782,31 +895,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterCompositeSerialize(apiResponse, outerComposite); + } return apiResponse; } @@ -814,7 +920,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterCompositeSerialize(e, "/fake/outer/composite", uriBuilder.Path, outerComposite); throw; } } @@ -838,6 +944,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual decimal? OnFakeOuterNumberSerialize(decimal? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterNumberSerialize(ApiResponse apiResponse, decimal? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterNumberSerialize(Exception exception, string pathFormat, string path, decimal? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer number types /// @@ -847,11 +984,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterNumberSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -861,6 +1001,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -870,7 +1012,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -880,31 +1022,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterNumberSerialize(apiResponse, body); + } return apiResponse; } @@ -912,7 +1047,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterNumberSerialize(e, "/fake/outer/number", uriBuilder.Path, body); throw; } } @@ -936,6 +1071,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnFakeOuterStringSerialize(string body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterStringSerialize(ApiResponse apiResponse, string body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterStringSerialize(Exception exception, string pathFormat, string path, string body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer string types /// @@ -945,11 +1111,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterStringSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -959,6 +1128,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -968,7 +1139,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -978,31 +1149,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterStringSerialize(apiResponse, body); + } return apiResponse; } @@ -1010,7 +1174,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterStringSerialize(e, "/fake/outer/string", uriBuilder.Path, body); throw; } } @@ -1053,6 +1217,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetArrayOfEnums() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetArrayOfEnums(ApiResponse> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetArrayOfEnums(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Array of Enums /// @@ -1061,16 +1253,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetArrayOfEnums(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/array-of-enums"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -1081,31 +1278,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetArrayOfEnums(apiResponse); + } return apiResponse; } @@ -1113,7 +1303,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetArrayOfEnums(e, "/fake/array-of-enums", uriBuilder.Path); throw; } } @@ -1158,6 +1348,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual FileSchemaTestClass OnTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (fileSchemaTestClass == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return fileSchemaTestClass; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestBodyWithFileSchema(ApiResponse apiResponse, FileSchemaTestClass fileSchemaTestClass) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithFileSchema(Exception exception, string pathFormat, string path, FileSchemaTestClass fileSchemaTestClass) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// For this test, the body for this request much reference a schema named `File`. /// @@ -1167,18 +1397,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (fileSchemaTestClass == null) - throw new ArgumentNullException(nameof(fileSchemaTestClass)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + fileSchemaTestClass = OnTestBodyWithFileSchema(fileSchemaTestClass); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1188,6 +1414,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(fileSchemaTestClass, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1197,32 +1425,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithFileSchema(apiResponse, fileSchemaTestClass); + } return apiResponse; } @@ -1230,7 +1451,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithFileSchema(e, "/fake/body-with-file-schema", uriBuilder.Path, fileSchemaTestClass); throw; } } @@ -1239,13 +1460,13 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1257,16 +1478,16 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsOrDefaultAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1277,31 +1498,72 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnTestBodyWithQueryParams(User user, string query) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (query == null) + throw new ArgumentNullException(nameof(query)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, query); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestBodyWithQueryParams(ApiResponse apiResponse, User user, string query) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithQueryParams(Exception exception, string pathFormat, string path, User user, string query) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (query == null) - throw new ArgumentNullException(nameof(query)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestBodyWithQueryParams(user, query); + user = validatedParameters.Item1; + query = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1317,6 +1579,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1326,32 +1590,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithQueryParams(apiResponse, user, query); + } return apiResponse; } @@ -1359,7 +1616,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithQueryParams(e, "/fake/body-with-query-params", uriBuilder.Path, user, query); throw; } } @@ -1404,6 +1661,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClientModel(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClientModel(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClientModel(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test \"client\" model To test \"client\" model /// @@ -1413,18 +1710,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClientModel(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1434,6 +1727,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1443,7 +1738,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1453,31 +1748,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClientModel(apiResponse, modelClient); + } return apiResponse; } @@ -1485,7 +1773,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClientModel(e, "/fake", uriBuilder.Path, modelClient); throw; } } @@ -1494,25 +1782,25 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1524,28 +1812,28 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersOrDefaultAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersOrDefaultAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1556,43 +1844,138 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (byte[], decimal, double, string, DateTime?, System.IO.Stream, float?, int?, int?, long?, string, string, string, DateTime?) OnTestEndpointParameters(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_byte == null) + throw new ArgumentNullException(nameof(_byte)); + + if (number == null) + throw new ArgumentNullException(nameof(number)); + + if (_double == null) + throw new ArgumentNullException(nameof(_double)); + + if (patternWithoutDelimiter == null) + throw new ArgumentNullException(nameof(patternWithoutDelimiter)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEndpointParameters(ApiResponse apiResponse, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEndpointParameters(Exception exception, string pathFormat, string path, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (patternWithoutDelimiter == null) - throw new ArgumentNullException(nameof(patternWithoutDelimiter)); - - if (_byte == null) - throw new ArgumentNullException(nameof(_byte)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + _byte = validatedParameters.Item1; + number = validatedParameters.Item2; + _double = validatedParameters.Item3; + patternWithoutDelimiter = validatedParameters.Item4; + date = validatedParameters.Item5; + binary = validatedParameters.Item6; + _float = validatedParameters.Item7; + integer = validatedParameters.Item8; + int32 = validatedParameters.Item9; + int64 = validatedParameters.Item10; + _string = validatedParameters.Item11; + password = validatedParameters.Item12; + callback = validatedParameters.Item13; + dateTime = validatedParameters.Item14; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1606,13 +1989,28 @@ namespace Org.OpenAPITools.Api multipartContent.Add(new FormUrlEncodedContent(formParams)); + formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + + + formParams.Add(new KeyValuePair("number", ClientUtils.ParameterToString(number))); + + formParams.Add(new KeyValuePair("double", ClientUtils.ParameterToString(_double))); + + formParams.Add(new KeyValuePair("pattern_without_delimiter", ClientUtils.ParameterToString(patternWithoutDelimiter))); - formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + if (date != null) + formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); + + if (binary != null) + multipartContent.Add(new StreamContent(binary)); + + if (_float != null) + formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); if (integer != null) formParams.Add(new KeyValuePair("integer", ClientUtils.ParameterToString(integer))); @@ -1623,18 +2021,9 @@ namespace Org.OpenAPITools.Api if (int64 != null) formParams.Add(new KeyValuePair("int64", ClientUtils.ParameterToString(int64))); - if (_float != null) - formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); - if (_string != null) formParams.Add(new KeyValuePair("string", ClientUtils.ParameterToString(_string))); - if (binary != null) - multipartContent.Add(new StreamContent(binary)); - - if (date != null) - formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); - if (password != null) formParams.Add(new KeyValuePair("password", ClientUtils.ParameterToString(password))); @@ -1646,6 +2035,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BasicToken basicToken = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1661,32 +2052,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEndpointParameters(apiResponse, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1697,7 +2081,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEndpointParameters(e, "/fake", uriBuilder.Path, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); throw; } } @@ -1708,17 +2092,17 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1732,20 +2116,20 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersOrDefaultAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersOrDefaultAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1756,27 +2140,90 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (List, List, double?, int?, List, string, string, string) OnTestEnumParameters(List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + return (enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEnumParameters(ApiResponse apiResponse, List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEnumParameters(Exception exception, string pathFormat, string path, List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + var validatedParameters = OnTestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + enumHeaderStringArray = validatedParameters.Item1; + enumQueryStringArray = validatedParameters.Item2; + enumQueryDouble = validatedParameters.Item3; + enumQueryInteger = validatedParameters.Item4; + enumFormStringArray = validatedParameters.Item5; + enumHeaderString = validatedParameters.Item6; + enumQueryString = validatedParameters.Item7; + enumFormString = validatedParameters.Item8; + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1786,12 +2233,12 @@ namespace Org.OpenAPITools.Api if (enumQueryStringArray != null) parseQueryString["enum_query_string_array"] = Uri.EscapeDataString(enumQueryStringArray.ToString()); - if (enumQueryInteger != null) - parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()); - if (enumQueryDouble != null) parseQueryString["enum_query_double"] = Uri.EscapeDataString(enumQueryDouble.ToString()); + if (enumQueryInteger != null) + parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()); + if (enumQueryString != null) parseQueryString["enum_query_string"] = Uri.EscapeDataString(enumQueryString.ToString()); @@ -1809,14 +2256,14 @@ namespace Org.OpenAPITools.Api List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (enumFormStringArray != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (enumFormStringArray != null) formParams.Add(new KeyValuePair("enum_form_string_array", ClientUtils.ParameterToString(enumFormStringArray))); if (enumFormString != null) formParams.Add(new KeyValuePair("enum_form_string", ClientUtils.ParameterToString(enumFormString))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1826,32 +2273,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEnumParameters(apiResponse, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } return apiResponse; } @@ -1859,7 +2299,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEnumParameters(e, "/fake", uriBuilder.Path, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); throw; } } @@ -1868,17 +2308,17 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1890,20 +2330,20 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersOrDefaultAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1914,29 +2354,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (bool, int, long, bool?, int?, long?) OnTestGroupParameters(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredBooleanGroup == null) + throw new ArgumentNullException(nameof(requiredBooleanGroup)); + + if (requiredStringGroup == null) + throw new ArgumentNullException(nameof(requiredStringGroup)); + + if (requiredInt64Group == null) + throw new ArgumentNullException(nameof(requiredInt64Group)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestGroupParameters(ApiResponse apiResponse, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestGroupParameters(Exception exception, string pathFormat, string path, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + requiredBooleanGroup = validatedParameters.Item1; + requiredStringGroup = validatedParameters.Item2; + requiredInt64Group = validatedParameters.Item3; + booleanGroup = validatedParameters.Item4; + stringGroup = validatedParameters.Item5; + int64Group = validatedParameters.Item6; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1962,6 +2468,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BearerToken bearerToken = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1972,28 +2480,21 @@ namespace Org.OpenAPITools.Api request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestGroupParameters(apiResponse, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -2004,7 +2505,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestGroupParameters(e, "/fake", uriBuilder.Path, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); throw; } } @@ -2049,6 +2550,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Dictionary OnTestInlineAdditionalProperties(Dictionary requestBody) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return requestBody; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestInlineAdditionalProperties(ApiResponse apiResponse, Dictionary requestBody) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestInlineAdditionalProperties(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test inline additionalProperties /// @@ -2058,18 +2599,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requestBody == null) - throw new ArgumentNullException(nameof(requestBody)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + requestBody = OnTestInlineAdditionalProperties(requestBody); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2079,6 +2616,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2088,32 +2627,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestInlineAdditionalProperties(apiResponse, requestBody); + } return apiResponse; } @@ -2121,7 +2653,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestInlineAdditionalProperties(e, "/fake/inline-additionalProperties", uriBuilder.Path, requestBody); throw; } } @@ -2168,6 +2700,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnTestJsonFormData(string param, string param2) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (param == null) + throw new ArgumentNullException(nameof(param)); + + if (param2 == null) + throw new ArgumentNullException(nameof(param2)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (param, param2); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestJsonFormData(ApiResponse apiResponse, string param, string param2) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestJsonFormData(Exception exception, string pathFormat, string path, string param, string param2) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test json serialization of form data /// @@ -2178,21 +2756,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (param == null) - throw new ArgumentNullException(nameof(param)); - - if (param2 == null) - throw new ArgumentNullException(nameof(param2)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestJsonFormData(param, param2); + param = validatedParameters.Item1; + param2 = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2208,8 +2781,12 @@ namespace Org.OpenAPITools.Api formParams.Add(new KeyValuePair("param", ClientUtils.ParameterToString(param))); + + formParams.Add(new KeyValuePair("param2", ClientUtils.ParameterToString(param2))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2219,32 +2796,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestJsonFormData(apiResponse, param, param2); + } return apiResponse; } @@ -2252,7 +2822,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestJsonFormData(e, "/fake/jsonFormData", uriBuilder.Path, param, param2); throw; } } @@ -2305,6 +2875,70 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + protected virtual (List, List, List, List, List) OnTestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + 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)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (pipe, ioutil, http, url, context); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestQueryParameterCollectionFormat(ApiResponse apiResponse, List pipe, List ioutil, List http, List url, List context) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestQueryParameterCollectionFormat(Exception exception, string pathFormat, string path, List pipe, List ioutil, List http, List url, List context) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test the collection format in query parameters /// @@ -2318,30 +2952,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - 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)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + pipe = validatedParameters.Item1; + ioutil = validatedParameters.Item2; + http = validatedParameters.Item3; + url = validatedParameters.Item4; + context = validatedParameters.Item5; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2357,32 +2980,27 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestQueryParameterCollectionFormat(apiResponse, pipe, ioutil, http, url, context); + } return apiResponse; } @@ -2390,8 +3008,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestQueryParameterCollectionFormat(e, "/fake/test-query-parameters", uriBuilder.Path, pipe, ioutil, http, url, context); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 321be9fcde0..07d8973b740 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeClassnameTags123Api : IApi { @@ -48,21 +49,19 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); } + Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + public partial class FakeClassnameTags123Api : IApi.IFakeClassnameTags123Api { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -119,6 +118,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -159,6 +167,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClassname(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClassname(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClassname(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -168,26 +216,22 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClassname(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake_classname_test"; - System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); - request.Content = (modelClient as object) is System.IO.Stream stream + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); request.Content = (modelClient as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); @@ -210,7 +254,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -220,31 +264,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Patch; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClassname(apiResponse, modelClient); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -255,8 +292,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClassname(e, "/fake_classname_test", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 00000000000..038f19bcfa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs index 53546aadb16..33b932d41a8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IPetApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + /// /// Deletes a pet /// @@ -74,6 +76,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeletePetAsync(long petId, string apiKey = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// Finds Pets by status /// @@ -97,6 +100,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null); + /// /// Finds Pets by tags /// @@ -120,6 +124,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null); + /// /// Find pet by ID /// @@ -143,6 +148,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Pet> Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Update an existing pet /// @@ -166,6 +172,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + /// /// Updates a pet in the store with form data /// @@ -193,19 +200,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task UpdatePetWithFormAsync(long petId, string name = null, string status = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server (optional) - /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<ApiResponse>> - Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image @@ -215,24 +209,25 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task of ApiResponse<ApiResponse> - Task UploadFileAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// uploads an image (required) - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// file to upload /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task<ApiResponse<ApiResponse>> - Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = 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. + /// Task of ApiResponse<ApiResponse> + Task UploadFileAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image (required) @@ -241,26 +236,38 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// ID of pet to update /// 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> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<ApiResponse> - Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); } + Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class PetApi : IPetApi + public partial class PetApi : IApi.IPetApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -317,6 +324,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Add a new pet to the store /// @@ -357,6 +373,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnAddPet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterAddPet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorAddPet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Add a new pet to the store /// @@ -366,22 +422,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> AddPetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnAddPet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress.Host; - uriBuilder.Port = HttpClient.BaseAddress.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -389,6 +441,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -413,32 +467,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterAddPet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -452,7 +499,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorAddPet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -499,6 +546,49 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (long, string) OnDeletePet(long petId, string apiKey) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, apiKey); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterDeletePet(ApiResponse apiResponse, long petId, string apiKey) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorDeletePet(Exception exception, string pathFormat, string path, long petId, string apiKey) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Deletes a pet /// @@ -509,26 +599,28 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnDeletePet(petId, apiKey); + petId = validatedParameters.Item1; + apiKey = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - if (apiKey != null) + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); if (apiKey != null) request.Headers.Add("api_key", ClientUtils.ParameterToString(apiKey)); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -539,28 +631,21 @@ namespace Org.OpenAPITools.Api request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeletePet(apiResponse, petId, apiKey); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -571,7 +656,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeletePet(e, "/pet/{petId}", uriBuilder.Path, petId, apiKey); throw; } } @@ -616,6 +701,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByStatus(List status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (status == null) + throw new ArgumentNullException(nameof(status)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return status; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByStatus(ApiResponse> apiResponse, List status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByStatus(Exception exception, string pathFormat, string path, List status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by status Multiple status values can be provided with comma separated strings /// @@ -625,18 +750,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> FindPetsByStatusWithHttpInfoAsync(List status, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (status == null) - throw new ArgumentNullException(nameof(status)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + status = OnFindPetsByStatus(status); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -650,6 +771,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -675,31 +798,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByStatus(apiResponse, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -713,7 +829,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByStatus(e, "/pet/findByStatus", uriBuilder.Path, status); throw; } } @@ -758,6 +874,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByTags(List tags) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return tags; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByTags(ApiResponse> apiResponse, List tags) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByTags(Exception exception, string pathFormat, string path, List tags) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @@ -767,18 +923,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> FindPetsByTagsWithHttpInfoAsync(List tags, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (tags == null) - throw new ArgumentNullException(nameof(tags)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + tags = OnFindPetsByTags(tags); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -792,6 +944,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -817,31 +971,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByTags(apiResponse, tags); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -855,7 +1002,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByTags(e, "/pet/findByTags", uriBuilder.Path, tags); throw; } } @@ -900,6 +1047,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetPetById(long petId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return petId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetPetById(ApiResponse apiResponse, long petId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetPetById(Exception exception, string pathFormat, string path, long petId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find pet by ID Returns a single pet /// @@ -909,22 +1096,20 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetPetByIdWithHttpInfoAsync(long petId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + petId = OnGetPetById(petId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokens = new List(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); List tokens = new List(); ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -943,31 +1128,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetPetById(apiResponse, petId); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -978,7 +1156,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetPetById(e, "/pet/{petId}", uriBuilder.Path, petId); throw; } } @@ -1023,6 +1201,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnUpdatePet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterUpdatePet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Update an existing pet /// @@ -1032,22 +1250,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnUpdatePet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress.Host; - uriBuilder.Port = HttpClient.BaseAddress.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -1055,6 +1269,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1079,32 +1295,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1118,7 +1327,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -1167,6 +1376,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, string, string) OnUpdatePetWithForm(long petId, string name, string status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, name, status); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUpdatePetWithForm(ApiResponse apiResponse, long petId, string name, string status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePetWithForm(Exception exception, string pathFormat, string path, long petId, string name, string status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updates a pet in the store with form data /// @@ -1178,30 +1433,29 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = null, string status = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdatePetWithForm(petId, name, status); + petId = validatedParameters.Item1; + name = validatedParameters.Item2; + status = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (name != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (name != null) formParams.Add(new KeyValuePair("name", ClientUtils.ParameterToString(name))); if (status != null) @@ -1209,6 +1463,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1224,32 +1480,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePetWithForm(apiResponse, petId, name, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1260,7 +1509,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePetWithForm(e, "/pet/{petId}", uriBuilder.Path, petId, name, status); throw; } } @@ -1270,13 +1519,13 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1289,16 +1538,16 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileOrDefaultAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileOrDefaultAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1309,48 +1558,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, System.IO.Stream, string) OnUploadFile(long petId, System.IO.Stream file, string additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, file, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFile(ApiResponse apiResponse, long petId, System.IO.Stream file, string additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFile(Exception exception, string pathFormat, string path, long petId, System.IO.Stream file, string additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFile(petId, file, additionalMetadata); + petId = validatedParameters.Item1; + file = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}/uploadImage"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (file != null) + multipartContent.Add(new StreamContent(file)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); - if (file != null) - multipartContent.Add(new StreamContent(file)); - List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1366,7 +1662,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1376,31 +1672,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFile(apiResponse, petId, file, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1411,7 +1700,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFile(e, "/pet/{petId}/uploadImage", uriBuilder.Path, petId, file, additionalMetadata); throw; } } @@ -1420,14 +1709,14 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1439,17 +1728,17 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileOrDefaultAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1460,50 +1749,97 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (System.IO.Stream, long, string) OnUploadFileWithRequiredFile(System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredFile == null) + throw new ArgumentNullException(nameof(requiredFile)); + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredFile, petId, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFileWithRequiredFile(ApiResponse apiResponse, System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFileWithRequiredFile(Exception exception, string pathFormat, string path, System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// 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> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requiredFile == null) - throw new ArgumentNullException(nameof(requiredFile)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); + requiredFile = validatedParameters.Item1; + petId = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/{petId}/uploadImageWithRequiredFile"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - multipartContent.Add(new StreamContent(requiredFile)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); multipartContent.Add(new StreamContent(requiredFile)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1519,7 +1855,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json", @@ -1530,31 +1866,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFileWithRequiredFile(apiResponse, requiredFile, petId, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1565,8 +1894,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFileWithRequiredFile(e, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path, requiredFile, petId, additionalMetadata); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs index e8a5a11078b..168268cb800 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IStoreApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Returns pet inventories by status /// @@ -70,6 +72,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Dictionary<string, int>> Task> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// Find purchase order by ID /// @@ -93,6 +96,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Place an order for a pet /// @@ -115,21 +119,19 @@ namespace Org.OpenAPITools.Api /// order placed for purchasing the pet /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> - Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); } + Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class StoreApi : IStoreApi + public partial class StoreApi : IApi.IStoreApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -186,6 +188,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -226,6 +237,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteOrder(string orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteOrder(ApiResponse apiResponse, string orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteOrder(Exception exception, string pathFormat, string path, string orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -235,50 +286,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteOrderWithHttpInfoAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (orderId == null) - throw new ArgumentNullException(nameof(orderId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnDeleteOrder(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteOrder(apiResponse, orderId); + } return apiResponse; } @@ -286,7 +327,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteOrder(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -309,6 +350,34 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetInventory() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetInventory(ApiResponse> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetInventory(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// @@ -317,11 +386,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> GetInventoryWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetInventory(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -345,31 +417,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetInventory(apiResponse); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -380,7 +445,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetInventory(e, "/store/inventory", uriBuilder.Path); throw; } } @@ -425,6 +490,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetOrderById(long orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetOrderById(ApiResponse apiResponse, long orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetOrderById(Exception exception, string pathFormat, string path, long orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions /// @@ -434,19 +539,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetOrderByIdWithHttpInfoAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnGetOrderById(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; @@ -460,31 +565,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetOrderById(apiResponse, orderId); + } return apiResponse; } @@ -492,7 +590,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetOrderById(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -537,6 +635,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Order OnPlaceOrder(Order order) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (order == null) + throw new ArgumentNullException(nameof(order)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return order; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterPlaceOrder(ApiResponse apiResponse, Order order) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorPlaceOrder(Exception exception, string pathFormat, string path, Order order) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Place an order for a pet /// @@ -546,18 +684,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> PlaceOrderWithHttpInfoAsync(Order order, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (order == null) - throw new ArgumentNullException(nameof(order)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + order = OnPlaceOrder(order); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -567,6 +701,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(order, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -576,7 +712,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/xml", @@ -587,31 +723,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterPlaceOrder(apiResponse, order); + } return apiResponse; } @@ -619,8 +748,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorPlaceOrder(e, "/store/order", uriBuilder.Path, order); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs index 4c1b0c68468..541b8c83155 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IUserApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Creates list of users with given input array /// @@ -72,6 +74,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Creates list of users with given input array /// @@ -95,6 +98,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Delete user /// @@ -118,6 +122,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + /// /// Get user by user name /// @@ -141,6 +146,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<User> Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + /// /// Logs user into the system /// @@ -166,6 +172,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null); + /// /// Logs out current logged in user session /// @@ -187,6 +194,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// Updated user /// @@ -194,11 +202,11 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task<ApiResponse<object>> - Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); + Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Updated user @@ -207,25 +215,23 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); } + Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class UserApi : IUserApi + public partial class UserApi : IApi.IUserApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -282,6 +288,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Create user This can only be done by the logged in user. /// @@ -322,6 +337,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual User OnCreateUser(User user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUser(ApiResponse apiResponse, User user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUser(Exception exception, string pathFormat, string path, User user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Create user This can only be done by the logged in user. /// @@ -331,18 +386,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUserWithHttpInfoAsync(User user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUser(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -352,6 +403,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -361,32 +414,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUser(apiResponse, user); + } return apiResponse; } @@ -394,7 +440,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUser(e, "/user", uriBuilder.Path, user); throw; } } @@ -439,6 +485,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithArrayInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithArrayInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithArrayInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -448,18 +534,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithArrayInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -469,6 +551,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -478,32 +562,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithArrayInput(apiResponse, user); + } return apiResponse; } @@ -511,7 +588,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithArrayInput(e, "/user/createWithArray", uriBuilder.Path, user); throw; } } @@ -556,6 +633,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithListInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithListInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithListInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -565,18 +682,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithListInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithListInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -586,6 +699,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -595,32 +710,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Post; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithListInput(apiResponse, user); + } return apiResponse; } @@ -628,7 +736,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithListInput(e, "/user/createWithList", uriBuilder.Path, user); throw; } } @@ -673,6 +781,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteUser(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteUser(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteUser(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete user This can only be done by the logged in user. /// @@ -682,50 +830,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteUserWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnDeleteUser(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Delete; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteUser(apiResponse, username); + } return apiResponse; } @@ -733,7 +871,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteUser(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -778,6 +916,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnGetUserByName(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetUserByName(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetUserByName(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Get user by user name /// @@ -787,22 +965,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetUserByNameWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnGetUserByName(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; @@ -816,31 +991,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetUserByName(apiResponse, username); + } return apiResponse; } @@ -848,7 +1016,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetUserByName(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -873,6 +1041,52 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnLoginUser(string username, string password) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + if (password == null) + throw new ArgumentNullException(nameof(password)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (username, password); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterLoginUser(ApiResponse apiResponse, string username, string password) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorLoginUser(Exception exception, string pathFormat, string path, string username, string password) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs user into the system /// @@ -883,21 +1097,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LoginUserWithHttpInfoAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (password == null) - throw new ArgumentNullException(nameof(password)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnLoginUser(username, password); + username = validatedParameters.Item1; + password = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -910,6 +1119,8 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -921,31 +1132,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLoginUser(apiResponse, username, password); + } return apiResponse; } @@ -953,7 +1157,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLoginUser(e, "/user/login", uriBuilder.Path, username, password); throw; } } @@ -996,6 +1200,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnLogoutUser() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterLogoutUser(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorLogoutUser(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs out current logged in user session /// @@ -1004,42 +1236,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LogoutUserWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnLogoutUser(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/logout"; + + request.RequestUri = uriBuilder.Uri; request.Method = HttpMethod.Get; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLogoutUser(apiResponse); + } return apiResponse; } @@ -1047,7 +1277,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLogoutUser(e, "/user/logout", uriBuilder.Path); throw; } } @@ -1056,13 +1286,13 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1074,16 +1304,16 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserOrDefaultAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1094,41 +1324,83 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnUpdateUser(User user, string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, username); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterUpdateUser(ApiResponse apiResponse, User user, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdateUser(Exception exception, string pathFormat, string path, User user, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdateUser(user, username); + user = validatedParameters.Item1; + username = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); - request.Content = (user as object) is System.IO.Stream stream + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.Content = (user as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1138,32 +1410,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = HttpMethod.Put; + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdateUser(apiResponse, user, username); + } return apiResponse; } @@ -1171,8 +1436,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdateUser(e, "/user/{username}", uriBuilder.Path, user, username); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 00000000000..7757b89c191 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.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.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs index f63fd593329..5cc9c254920 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -16,22 +16,12 @@ namespace Org.OpenAPITools.Client /// /// /// - /// + /// public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { _raw = $"{ prefix }{ value }"; } - /// - /// Places the token in the cookie. - /// - /// - /// - public virtual void UseInCookie(System.Net.Http.HttpRequestMessage request, string cookieName) - { - request.Headers.Add("Cookie", $"{ cookieName }=_raw"); - } - /// /// Places the token in the header. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs index e5da6000321..f87e53e8b04 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -12,35 +12,46 @@ namespace Org.OpenAPITools.Client /// The time the request was sent. /// public DateTime RequestedAt { get; } + /// /// The time the response was received. /// public DateTime ReceivedAt { get; } + /// /// The HttpStatusCode received. /// public HttpStatusCode HttpStatus { get; } + /// /// The path requested. /// - public string Path { get; } + public string PathFormat { get; } + /// /// The elapsed time from request to response. /// public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + /// + /// The path + /// + public string Path { get; } + /// /// The event args used to track server health. /// /// /// /// + /// /// - public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string path) + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) { RequestedAt = requestedAt; ReceivedAt = receivedAt; HttpStatus = httpStatus; + PathFormat = pathFormat; Path = path; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs index 3bae0aaa6ab..0a8a0769c19 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -34,6 +34,11 @@ namespace Org.OpenAPITools.Client /// The raw content of this response /// string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } } /// @@ -41,12 +46,10 @@ namespace Org.OpenAPITools.Client /// public partial class ApiResponse : IApiResponse { - #region Properties - /// /// The deserialized content /// - public T Content { get; set; } + public T Content { get; internal set; } /// /// Gets or sets the status code (HTTP status code) @@ -82,7 +85,10 @@ namespace Org.OpenAPITools.Client /// public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } - #endregion Properties + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; /// /// Construct the response using an HttpResponseMessage diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs index 4ac8055d7df..2d16402e3ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -10,16 +10,9 @@ using System; using System.IO; using System.Linq; -using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Polly.Timeout; -using Polly.Extensions.Http; -using Polly; -using Org.OpenAPITools.Api; using KellermanSoftware.CompareNetObjects; namespace Org.OpenAPITools.Client @@ -280,114 +273,5 @@ namespace Org.OpenAPITools.Client /// The format to use for DateTime serialization /// public const string ISO8601_DATETIME_FORMAT = "o"; - - /// - /// 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, config); - - AddApi(services, config); - }); - - return builder; - } - - /// - /// Add the api to your host builder. - /// - /// - /// - public static void AddApi(this IServiceCollection services, Action options) - { - HostConfiguration config = new HostConfiguration(services); - options(config); - AddApi(services, config); - } - - private static void AddApi(IServiceCollection services, HostConfiguration host) - { - if (!host.HttpClientsAdded) - host.AddApiHttpClients(); - - // 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))); - } - } - } - - /// - /// 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 circiut 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 00000000000..da94287dab8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,18 @@ +// + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 00000000000..47daa5b77e5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * 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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 00000000000..02d9e10ba7e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs index e3200ba2391..49dd0278de5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -14,7 +14,6 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Net.Http; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client @@ -22,10 +21,17 @@ namespace Org.OpenAPITools.Client /// /// Provides hosting configuration for Org.OpenAPITools /// - public class HostConfiguration + public class HostConfiguration + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi { private readonly IServiceCollection _services; - private JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); internal bool HttpClientsAdded { get; private set; } @@ -37,35 +43,101 @@ namespace Org.OpenAPITools.Client { _services = services; _jsonOptions.Converters.Add(new JsonStringEnumConverter()); - _jsonOptions.Converters.Add(new OpenAPIDateJsonConverter()); + _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 CatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new CategoryJsonConverter()); _jsonOptions.Converters.Add(new ChildCatJsonConverter()); + _jsonOptions.Converters.Add(new ChildCatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new ClassModelJsonConverter()); _jsonOptions.Converters.Add(new ComplexQuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new DanishPigJsonConverter()); + _jsonOptions.Converters.Add(new DeprecatedObjectJsonConverter()); _jsonOptions.Converters.Add(new DogJsonConverter()); + _jsonOptions.Converters.Add(new DogAllOfJsonConverter()); + _jsonOptions.Converters.Add(new DrawingJsonConverter()); + _jsonOptions.Converters.Add(new EnumArraysJsonConverter()); + _jsonOptions.Converters.Add(new EnumClassConverter()); + _jsonOptions.Converters.Add(new EnumClassNullableConverter()); + _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 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 NullableClassJsonConverter()); _jsonOptions.Converters.Add(new NullableShapeJsonConverter()); + _jsonOptions.Converters.Add(new NumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ObjectWithDeprecatedFieldsJsonConverter()); + _jsonOptions.Converters.Add(new OrderJsonConverter()); + _jsonOptions.Converters.Add(new OuterCompositeJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumConverter()); + _jsonOptions.Converters.Add(new OuterEnumNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueNullableConverter()); _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 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 TriangleJsonConverter()); + _jsonOptions.Converters.Add(new TriangleInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new WhaleJsonConverter()); + _jsonOptions.Converters.Add(new ZebraJsonConverter()); _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); } /// @@ -74,29 +146,22 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddApiHttpClients + public HostConfiguration AddApiHttpClients ( Action client = null, Action builder = null) - where TAnotherFakeApi : class, IAnotherFakeApi - where TDefaultApi : class, IDefaultApi - where TFakeApi : class, IFakeApi - where TFakeClassnameTags123Api : class, IFakeClassnameTags123Api - where TPetApi : class, IPetApi - where TStoreApi : class, IStoreApi - where TUserApi : class, IUserApi { 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)); + + 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) @@ -107,25 +172,12 @@ namespace Org.OpenAPITools.Client return this; } - /// - /// Configures the HttpClients. - /// - /// - /// - /// - public HostConfiguration AddApiHttpClients(Action client = null, Action builder = null) - { - AddApiHttpClients(client, builder); - - return this; - } - /// /// Configures the JsonSerializerSettings /// /// /// - public HostConfiguration ConfigureJsonOptions(Action options) + public HostConfiguration ConfigureJsonOptions(Action options) { options(_jsonOptions); @@ -138,7 +190,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase { return AddTokens(new TTokenBase[]{ token }); } @@ -149,7 +201,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase { TokenContainer container = new TokenContainer(tokens); _services.AddSingleton(services => container); @@ -163,7 +215,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration UseProvider() + public HostConfiguration UseProvider() where TTokenProvider : TokenProvider where TTokenBase : TokenBase { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/IApi.cs deleted file mode 100644 index bd74ad34fd3..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/IApi.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Net.Http; - -namespace Org.OpenAPITools.Client -{ - /// - /// Any Api client - /// - public interface IApi - { - /// - /// The HttpClient - /// - HttpClient HttpClient { get; } - - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - event ClientUtils.EventHandler ApiResponded; - } -} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs deleted file mode 100644 index a280076c5a9..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 Org.OpenAPITools.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 OpenAPIDateJsonConverter : JsonConverter - { - /// - /// Returns a DateTime from the Json object - /// - /// - /// - /// - /// - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => - DateTime.ParseExact(reader.GetString(), "yyyy-MM-dd", CultureInfo.InvariantCulture); - - /// - /// Writes the DateTime to the json writer - /// - /// - /// - /// - public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => - writer.WriteStringValue(dateTimeValue.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); - } -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 00000000000..deefb4ab70e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,57 @@ +/* + * 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.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 00000000000..a204267fa64 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.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.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.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 circiut 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 00000000000..b7cfb5f6f9c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,88 @@ +/* + * 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.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + 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-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs index 68647a4ae15..35452f5ff88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// test map of maps /// - public partial class Activity : IEquatable, IValidatableObject + public partial class Activity : IValidatableObject { /// /// Initializes a new instance of the class. /// /// activityOutputs - public Activity(Dictionary> activityOutputs = default) + [JsonConstructor] + public Activity(Dictionary> activityOutputs) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (activityOutputs == null) + throw new ArgumentNullException("activityOutputs is a required property for Activity and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ActivityOutputs = activityOutputs; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 Activity).AreEqual; - } - - /// - /// Returns true if Activity instances are equal - /// - /// Instance of Activity to be compared - /// Boolean - public bool Equals(Activity 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; - if (this.ActivityOutputs != null) - { - hashCode = (hashCode * 59) + this.ActivityOutputs.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Activity + /// + public class ActivityJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Activity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary> activityOutputs = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "activity_outputs": + activityOutputs = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new Activity(activityOutputs); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Activity activity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index ed290bab607..31ae89912fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// ActivityOutputElementRepresentation /// - public partial class ActivityOutputElementRepresentation : IEquatable, IValidatableObject + public partial class ActivityOutputElementRepresentation : IValidatableObject { /// /// Initializes a new instance of the class. /// /// prop1 /// prop2 - public ActivityOutputElementRepresentation(string prop1 = default, Object prop2 = default) + [JsonConstructor] + public ActivityOutputElementRepresentation(string prop1, Object prop2) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (prop1 == null) + throw new ArgumentNullException("prop1 is a required property for ActivityOutputElementRepresentation and cannot be null."); + + if (prop2 == null) + throw new ArgumentNullException("prop2 is a required property for ActivityOutputElementRepresentation and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Prop1 = prop1; Prop2 = prop2; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 ActivityOutputElementRepresentation).AreEqual; - } - - /// - /// Returns true if ActivityOutputElementRepresentation instances are equal - /// - /// Instance of ActivityOutputElementRepresentation to be compared - /// Boolean - public bool Equals(ActivityOutputElementRepresentation 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; - if (this.Prop1 != null) - { - hashCode = (hashCode * 59) + this.Prop1.GetHashCode(); - } - if (this.Prop2 != null) - { - hashCode = (hashCode * 59) + this.Prop2.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,77 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ActivityOutputElementRepresentation + /// + public class ActivityOutputElementRepresentationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string prop1 = default; + Object prop2 = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "prop1": + prop1 = reader.GetString(); + break; + case "prop2": + prop2 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new ActivityOutputElementRepresentation(prop1, prop2); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 25b11f890fa..5682c09e840 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,36 +26,65 @@ namespace Org.OpenAPITools.Model /// /// AdditionalPropertiesClass /// - public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class AdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty - /// anytype1 + /// mapProperty /// mapWithUndeclaredPropertiesAnytype1 /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 - /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapWithUndeclaredPropertiesString - public AdditionalPropertiesClass(Dictionary mapProperty = default, Dictionary> mapOfMapProperty = default, Object anytype1 = default, Object mapWithUndeclaredPropertiesAnytype1 = default, Object mapWithUndeclaredPropertiesAnytype2 = default, Dictionary mapWithUndeclaredPropertiesAnytype3 = default, Object emptyMap = default, Dictionary mapWithUndeclaredPropertiesString = default) + /// anytype1 + [JsonConstructor] + public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object anytype1 = default) { - MapProperty = mapProperty; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapProperty == null) + throw new ArgumentNullException("mapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapOfMapProperty == null) + throw new ArgumentNullException("mapOfMapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype1 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype2 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype3 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (emptyMap == null) + throw new ArgumentNullException("emptyMap is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesString is a required property for AdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + EmptyMap = emptyMap; MapOfMapProperty = mapOfMapProperty; - Anytype1 = anytype1; + MapProperty = mapProperty; MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - EmptyMap = emptyMap; MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + Anytype1 = anytype1; } /// - /// Gets or Sets MapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// - [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + /// 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 @@ -65,10 +93,10 @@ namespace Org.OpenAPITools.Model public Dictionary> MapOfMapProperty { get; set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapProperty /// - [JsonPropertyName("anytype_1")] - public Object Anytype1 { get; set; } + [JsonPropertyName("map_property")] + public Dictionary MapProperty { get; set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 @@ -88,24 +116,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("map_with_undeclared_properties_anytype_3")] public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } - /// - /// 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 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -115,88 +142,18 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); - sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).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(" EmptyMap: ").Append(EmptyMap).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesClass instances are equal - /// - /// Instance of AdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(AdditionalPropertiesClass 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; - if (this.MapProperty != null) - { - hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); - } - if (this.MapOfMapProperty != null) - { - hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); - } - if (this.Anytype1 != null) - { - hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype1 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype2 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype3 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); - } - if (this.EmptyMap != null) - { - hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesString != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -208,4 +165,114 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AdditionalPropertiesClass + /// + public class AdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "empty_map": + emptyMap = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_of_map_property": + mapOfMapProperty = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_property": + mapProperty = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_1": + mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_2": + mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_3": + mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_string": + mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref reader, options); + break; + case "anytype_1": + anytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, options); + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, options); + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, options); + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, options); + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs index 4d287b1d2fd..122d4658dd4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Animal /// - public partial class Animal : IEquatable, IValidatableObject + public partial class Animal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// color (default to "red") + [JsonConstructor] public Animal(string className, string color = "red") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for Animal and cannot be null."); + if (color == null) + throw new ArgumentNullException("color is a required property for Animal and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Color = color; } @@ -59,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 Animal).AreEqual; - } - - /// - /// Returns true if Animal instances are equal - /// - /// Instance of Animal to be compared - /// Boolean - public bool Equals(Animal 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +105,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Animal + /// + public class AnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + string color = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "color": + color = reader.GetString(); + break; + default: + break; + } + } + } + + return new Animal(className, color); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", animal.ClassName); + writer.WriteString("color", animal.Color); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs index 9410088a413..fba4da09247 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,19 +26,35 @@ namespace Org.OpenAPITools.Model /// /// ApiResponse /// - public partial class ApiResponse : IEquatable, IValidatableObject + public partial class ApiResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// /// code - /// type /// message - public ApiResponse(int code = default, string type = default, string message = default) + /// type + [JsonConstructor] + public ApiResponse(int code, string message, string type) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (code == null) + throw new ArgumentNullException("code is a required property for ApiResponse and cannot be null."); + + if (type == null) + throw new ArgumentNullException("type is a required property for ApiResponse and cannot be null."); + + if (message == null) + throw new ArgumentNullException("message is a required property for ApiResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Code = code; - Type = type; Message = message; + Type = type; } /// @@ -48,23 +63,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("code")] public int Code { get; set; } - /// - /// Gets or Sets Type - /// - [JsonPropertyName("type")] - public string Type { 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,59 +90,12 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); - sb.Append(" Type: ").Append(Type).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ApiResponse).AreEqual; - } - - /// - /// Returns true if ApiResponse instances are equal - /// - /// Instance of ApiResponse to be compared - /// Boolean - public bool Equals(ApiResponse 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) + this.Code.GetHashCode(); - if (this.Type != null) - { - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - } - if (this.Message != null) - { - hashCode = (hashCode * 59) + this.Message.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ApiResponse + /// + public class ApiResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ApiResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int code = default; + string message = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "code": + code = reader.GetInt32(); + break; + case "message": + message = reader.GetString(); + break; + case "type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new ApiResponse(code, message, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("code", (int)apiResponse.Code); + writer.WriteString("message", apiResponse.Message); + writer.WriteString("type", apiResponse.Type); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs index d6a9cf50290..2d5443fbd52 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Apple /// - public partial class Apple : IEquatable, IValidatableObject + public partial class Apple : IValidatableObject { /// /// Initializes a new instance of the class. /// /// cultivar /// origin - public Apple(string cultivar = default, string origin = default) + [JsonConstructor] + public Apple(string cultivar, string origin) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (cultivar == null) + throw new ArgumentNullException("cultivar is a required property for Apple and cannot be null."); + + if (origin == null) + throw new ArgumentNullException("origin is a required property for Apple and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Origin = origin; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 Apple).AreEqual; - } - - /// - /// Returns true if Apple instances are equal - /// - /// Instance of Apple to be compared - /// Boolean - public bool Equals(Apple 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - if (this.Origin != null) - { - hashCode = (hashCode * 59) + this.Origin.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -143,4 +109,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Apple + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + string origin = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "origin": + origin = reader.GetString(); + break; + default: + break; + } + } + } + + return new Apple(cultivar, origin); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", apple.Cultivar); + writer.WriteString("origin", apple.Origin); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs index 48e37cc0aa8..bae73be3242 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// AppleReq /// - public partial class AppleReq : IEquatable, IValidatableObject + public partial class AppleReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// cultivar (required) + /// cultivar /// mealy - public AppleReq(string cultivar, bool mealy = default) + [JsonConstructor] + public AppleReq(string cultivar, bool mealy) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (cultivar == null) throw new ArgumentNullException("cultivar is a required property for AppleReq and cannot be null."); + if (mealy == null) + throw new ArgumentNullException("mealy is a required property for AppleReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Mealy = mealy; } @@ -68,45 +77,6 @@ namespace Org.OpenAPITools.Model 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 AppleReq).AreEqual; - } - - /// - /// Returns true if AppleReq instances are equal - /// - /// Instance of AppleReq to be compared - /// Boolean - public bool Equals(AppleReq 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +88,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AppleReq + /// + public class AppleReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AppleReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + bool mealy = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "mealy": + mealy = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new AppleReq(cultivar, mealy); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", appleReq.Cultivar); + writer.WriteBoolean("mealy", appleReq.Mealy); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 256a6b596ad..ea6a1f3caba 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfArrayOfNumberOnly /// - public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayArrayNumber - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber = default) + [JsonConstructor] + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayArrayNumber == null) + throw new ArgumentNullException("arrayArrayNumber is a required property for ArrayOfArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayNumber = arrayArrayNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfArrayOfNumberOnly 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; - if (this.ArrayArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfArrayOfNumberOnly + /// + public class ArrayOfArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayArrayNumber": + arrayArrayNumber = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 6c462dddf1e..c09645642c6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfNumberOnly /// - public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayNumber - public ArrayOfNumberOnly(List arrayNumber = default) + [JsonConstructor] + public ArrayOfNumberOnly(List arrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayNumber == null) + throw new ArgumentNullException("arrayNumber is a required property for ArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayNumber = arrayNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfNumberOnly 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; - if (this.ArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfNumberOnly + /// + public class ArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayNumber": + arrayNumber = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfNumberOnly(arrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs index f9872d70105..ef26590ab3c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,37 @@ namespace Org.OpenAPITools.Model /// /// ArrayTest /// - public partial class ArrayTest : IEquatable, IValidatableObject + public partial class ArrayTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayOfString /// arrayArrayOfInteger /// arrayArrayOfModel - public ArrayTest(List arrayOfString = default, List> arrayArrayOfInteger = default, List> arrayArrayOfModel = default) + /// arrayOfString + [JsonConstructor] + public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) { - ArrayOfString = arrayOfString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayOfString == null) + throw new ArgumentNullException("arrayOfString is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfInteger == null) + throw new ArgumentNullException("arrayArrayOfInteger is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfModel == null) + throw new ArgumentNullException("arrayArrayOfModel is a required property for ArrayTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayOfInteger = arrayArrayOfInteger; ArrayArrayOfModel = arrayArrayOfModel; + ArrayOfString = arrayOfString; } - /// - /// Gets or Sets ArrayOfString - /// - [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } - /// /// Gets or Sets ArrayArrayOfInteger /// @@ -60,11 +69,17 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,63 +89,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); - sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayTest).AreEqual; - } - - /// - /// Returns true if ArrayTest instances are equal - /// - /// Instance of ArrayTest to be compared - /// Boolean - public bool Equals(ArrayTest 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; - if (this.ArrayOfString != null) - { - hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); - } - if (this.ArrayArrayOfInteger != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); - } - if (this.ArrayArrayOfModel != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +107,84 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayTest + /// + public class ArrayTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayOfInteger = default; + List> arrayArrayOfModel = default; + List arrayOfString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_array_of_integer": + arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_array_of_model": + arrayArrayOfModel = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_of_string": + arrayOfString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, options); + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, options); + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs index 3192691eb71..129aec2d593 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Banana /// - public partial class Banana : IEquatable, IValidatableObject + public partial class Banana : IValidatableObject { /// /// Initializes a new instance of the class. /// /// lengthCm - public Banana(decimal lengthCm = default) + [JsonConstructor] + public Banana(decimal lengthCm) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (lengthCm == null) + throw new ArgumentNullException("lengthCm is a required property for Banana and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 Banana).AreEqual; - } - - /// - /// Returns true if Banana instances are equal - /// - /// Instance of Banana to be compared - /// Boolean - public bool Equals(Banana 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) + this.LengthCm.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Banana + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Banana(lengthCm); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)banana.LengthCm); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs index 95ea0488f23..1ef87ba0994 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// BananaReq /// - public partial class BananaReq : IEquatable, IValidatableObject + public partial class BananaReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// lengthCm (required) + /// lengthCm /// sweet - public BananaReq(decimal lengthCm, bool sweet = default) + [JsonConstructor] + public BananaReq(decimal lengthCm, bool sweet) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (lengthCm == null) throw new ArgumentNullException("lengthCm is a required property for BananaReq and cannot be null."); + if (sweet == null) + throw new ArgumentNullException("sweet is a required property for BananaReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; Sweet = sweet; } @@ -68,42 +77,6 @@ namespace Org.OpenAPITools.Model 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 BananaReq).AreEqual; - } - - /// - /// Returns true if BananaReq instances are equal - /// - /// Instance of BananaReq to be compared - /// Boolean - public bool Equals(BananaReq 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) + this.LengthCm.GetHashCode(); - hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +88,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BananaReq + /// + public class BananaReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BananaReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + bool sweet = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + case "sweet": + sweet = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new BananaReq(lengthCm, sweet); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)bananaReq.LengthCm); + writer.WriteBoolean("sweet", bananaReq.Sweet); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs index fc19bc19279..de3bca6d08c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// BasquePig /// - public partial class BasquePig : IEquatable, IValidatableObject + public partial class BasquePig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public BasquePig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for BasquePig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 BasquePig).AreEqual; - } - - /// - /// Returns true if BasquePig instances are equal - /// - /// Instance of BasquePig to be compared - /// Boolean - public bool Equals(BasquePig 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BasquePig + /// + public class BasquePigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BasquePig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new BasquePig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", basquePig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs index 92d92494967..0d25bc70612 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,32 +26,58 @@ namespace Org.OpenAPITools.Model /// /// Capitalization /// - public partial class Capitalization : IEquatable, IValidatableObject + public partial class Capitalization : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// smallCamel + /// Name of the pet /// capitalCamel - /// smallSnake /// capitalSnake /// sCAETHFlowPoints - /// Name of the pet - public Capitalization(string smallCamel = default, string capitalCamel = default, string smallSnake = default, string capitalSnake = default, string sCAETHFlowPoints = default, string aTTNAME = default) + /// smallCamel + /// smallSnake + [JsonConstructor] + public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) { - SmallCamel = smallCamel; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (smallCamel == null) + throw new ArgumentNullException("smallCamel is a required property for Capitalization and cannot be null."); + + if (capitalCamel == null) + throw new ArgumentNullException("capitalCamel is a required property for Capitalization and cannot be null."); + + if (smallSnake == null) + throw new ArgumentNullException("smallSnake is a required property for Capitalization and cannot be null."); + + if (capitalSnake == null) + throw new ArgumentNullException("capitalSnake is a required property for Capitalization and cannot be null."); + + if (sCAETHFlowPoints == null) + throw new ArgumentNullException("sCAETHFlowPoints is a required property for Capitalization and cannot be null."); + + if (aTTNAME == null) + throw new ArgumentNullException("aTTNAME is a required property for Capitalization and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ATT_NAME = aTTNAME; CapitalCamel = capitalCamel; - SmallSnake = smallSnake; CapitalSnake = capitalSnake; SCAETHFlowPoints = sCAETHFlowPoints; - ATT_NAME = aTTNAME; + SmallCamel = smallCamel; + SmallSnake = smallSnake; } /// - /// Gets or Sets SmallCamel + /// Name of the pet /// - [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + /// Name of the pet + [JsonPropertyName("ATT_NAME")] + public string ATT_NAME { get; set; } /// /// Gets or Sets CapitalCamel @@ -60,12 +85,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("CapitalCamel")] public string CapitalCamel { get; set; } - /// - /// Gets or Sets SmallSnake - /// - [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } - /// /// Gets or Sets CapitalSnake /// @@ -79,17 +98,22 @@ namespace Org.OpenAPITools.Model public string SCAETHFlowPoints { get; set; } /// - /// Name of the pet + /// Gets or Sets SmallCamel /// - /// Name of the pet - [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -99,78 +123,16 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); - sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); - sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); - sb.Append(" ATT_NAME: ").Append(ATT_NAME).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Capitalization).AreEqual; - } - - /// - /// Returns true if Capitalization instances are equal - /// - /// Instance of Capitalization to be compared - /// Boolean - public bool Equals(Capitalization 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; - if (this.SmallCamel != null) - { - hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); - } - if (this.CapitalCamel != null) - { - hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); - } - if (this.SmallSnake != null) - { - hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); - } - if (this.CapitalSnake != null) - { - hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); - } - if (this.SCAETHFlowPoints != null) - { - hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); - } - if (this.ATT_NAME != null) - { - hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -182,4 +144,96 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Capitalization + /// + public class CapitalizationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Capitalization Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string aTTNAME = default; + string capitalCamel = default; + string capitalSnake = default; + string sCAETHFlowPoints = default; + string smallCamel = default; + string smallSnake = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ATT_NAME": + aTTNAME = reader.GetString(); + break; + case "CapitalCamel": + capitalCamel = reader.GetString(); + break; + case "Capital_Snake": + capitalSnake = reader.GetString(); + break; + case "SCA_ETH_Flow_Points": + sCAETHFlowPoints = reader.GetString(); + break; + case "smallCamel": + smallCamel = reader.GetString(); + break; + case "small_Snake": + smallSnake = reader.GetString(); + break; + default: + break; + } + } + } + + return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + 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); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs index b8c35dd406a..462e1e3d6ed 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,16 +26,17 @@ namespace Org.OpenAPITools.Model /// /// Cat /// - public partial class Cat : Animal, IEquatable + public partial class Cat : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - /// className (required) + /// className /// color (default to "red") - public Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string color = "red") : base(className, color) + [JsonConstructor] + internal Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string color = "red") : base(className, color) { Dictionary = dictionary; CatAllOf = catAllOf; @@ -64,40 +64,6 @@ namespace Org.OpenAPITools.Model 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 Cat).AreEqual; - } - - /// - /// Returns true if Cat instances are equal - /// - /// Instance of Cat to be compared - /// Boolean - public bool Equals(Cat 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -105,13 +71,6 @@ namespace Org.OpenAPITools.Model /// public class CatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Cat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -124,24 +83,29 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader dictionaryReader = reader; - bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref dictionaryReader, options, out Dictionary dictionary); + bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref reader, options, out Dictionary dictionary); Utf8JsonReader catAllOfReader = reader; - bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref catAllOfReader, options, out CatAllOf catAllOf); + bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out CatAllOf catAllOf); string className = default; string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -154,6 +118,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -168,6 +134,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", cat.ClassName); + writer.WriteString("color", cat.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/CatAllOf.cs index f1f19c6c88d..bdda4289814 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// CatAllOf /// - public partial class CatAllOf : IEquatable, IValidatableObject + public partial class CatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// declawed - public CatAllOf(bool declawed = default) + [JsonConstructor] + public CatAllOf(bool declawed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (declawed == null) + throw new ArgumentNullException("declawed is a required property for CatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Declawed = declawed; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 CatAllOf).AreEqual; - } - - /// - /// Returns true if CatAllOf instances are equal - /// - /// Instance of CatAllOf to be compared - /// Boolean - public bool Equals(CatAllOf 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) + this.Declawed.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type CatAllOf + /// + public class CatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override CatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool declawed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "declawed": + declawed = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new CatAllOf(declawed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CatAllOf catAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("declawed", catAllOf.Declawed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs index be6a1620b10..0a34203a8a4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,31 @@ namespace Org.OpenAPITools.Model /// /// Category /// - public partial class Category : IEquatable, IValidatableObject + public partial class Category : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) (default to "default-name") /// id - public Category(string name = "default-name", long id = default) + /// name (default to "default-name") + [JsonConstructor] + public Category(long id, string name = "default-name") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Category and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Category and cannot be null."); - Name = name; - Id = id; - } +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - /// - /// Gets or Sets Name - /// - [JsonPropertyName("name")] - public string Name { get; set; } + Id = id; + Name = name; + } /// /// Gets or Sets Id @@ -55,11 +58,17 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -69,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); - sb.Append(" Name: ").Append(Name).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Category).AreEqual; - } - - /// - /// Returns true if Category instances are equal - /// - /// Instance of Category to be compared - /// Boolean - public bool Equals(Category 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Category + /// + public class CategoryJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Category Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Category(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Category category, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)category.Id); + writer.WriteString("name", category.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs index 5245528adb8..eac43e23273 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ChildCat /// - public partial class ChildCat : ParentPet, IEquatable + public partial class ChildCat : ParentPet, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// petType (required) - public ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) + /// petType + [JsonConstructor] + internal ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) { ChildCatAllOf = childCatAllOf; } @@ -56,40 +56,6 @@ namespace Org.OpenAPITools.Model 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 ChildCat).AreEqual; - } - - /// - /// Returns true if ChildCat instances are equal - /// - /// Instance of ChildCat to be compared - /// Boolean - public bool Equals(ChildCat 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -97,13 +63,6 @@ namespace Org.OpenAPITools.Model /// public class ChildCatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ChildCat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -116,20 +75,25 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader childCatAllOfReader = reader; - bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref childCatAllOfReader, options, out ChildCatAllOf childCatAllOf); + bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ChildCatAllOf childCatAllOf); string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -139,6 +103,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -153,6 +119,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", childCat.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index bc601c217ba..6b768fcd1e7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// ChildCatAllOf /// - public partial class ChildCatAllOf : IEquatable, IValidatableObject + public partial class ChildCatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name /// petType (default to PetTypeEnum.ChildCat) - public ChildCatAllOf(string name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) + [JsonConstructor] + public ChildCatAllOf(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for ChildCatAllOf and cannot be null."); + + if (petType == null) + throw new ArgumentNullException("petType is a required property for ChildCatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; PetType = petType; } @@ -48,11 +60,37 @@ namespace Org.OpenAPITools.Model /// /// Enum ChildCat for value: ChildCat /// - [EnumMember(Value = "ChildCat")] ChildCat = 1 } + /// + /// Returns a PetTypeEnum + /// + /// + /// + public static PetTypeEnum PetTypeEnumFromString(string value) + { + if (value == "ChildCat") + return PetTypeEnum.ChildCat; + + throw new NotImplementedException($"Could not convert value to type PetTypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -69,7 +107,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -85,49 +123,6 @@ namespace Org.OpenAPITools.Model 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 ChildCatAllOf).AreEqual; - } - - /// - /// Returns true if ChildCatAllOf instances are equal - /// - /// Instance of ChildCatAllOf to be compared - /// Boolean - public bool Equals(ChildCatAllOf 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +134,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ChildCatAllOf + /// + public class ChildCatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ChildCatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + ChildCatAllOf.PetTypeEnum petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + case "pet_type": + string petTypeRawValue = reader.GetString(); + petType = ChildCatAllOf.PetTypeEnumFromString(petTypeRawValue); + break; + default: + break; + } + } + } + + return new ChildCatAllOf(name, petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChildCatAllOf childCatAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", childCatAllOf.Name); + var petTypeRawValue = ChildCatAllOf.PetTypeEnumToJsonValue(childCatAllOf.PetType); + if (petTypeRawValue != null) + writer.WriteString("pet_type", petTypeRawValue); + else + writer.WriteNull("pet_type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs index 84a40d94899..be70d0da28b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model with \"_class\" property /// - public partial class ClassModel : IEquatable, IValidatableObject + public partial class ClassModel : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _class - public ClassModel(string _class = default) + /// classProperty + [JsonConstructor] + public ClassModel(string classProperty) { - Class = _class; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for ClassModel and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; } /// - /// Gets or Sets Class + /// Gets or Sets ClassProperty /// [JsonPropertyName("_class")] - public string Class { get; set; } + public string ClassProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); - sb.Append(" Class: ").Append(Class).Append("\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).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 ClassModel).AreEqual; - } - - /// - /// Returns true if ClassModel instances are equal - /// - /// Instance of ClassModel to be compared - /// Boolean - public bool Equals(ClassModel 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; - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ClassModel + /// + public class ClassModelJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ClassModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_class": + classProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ClassModel(classProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_class", classModel.ClassProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 2ec6fa15f31..b4c3977c995 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ComplexQuadrilateral /// - public partial class ComplexQuadrilateral : IEquatable, IValidatableObject + public partial class ComplexQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 ComplexQuadrilateral).AreEqual; - } - - /// - /// Returns true if ComplexQuadrilateral instances are equal - /// - /// Instance of ComplexQuadrilateral to be compared - /// Boolean - public bool Equals(ComplexQuadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class ComplexQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ComplexQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs index fdcd66cce71..f0d02bc0b01 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DanishPig /// - public partial class DanishPig : IEquatable, IValidatableObject + public partial class DanishPig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public DanishPig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for DanishPig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DanishPig).AreEqual; - } - - /// - /// Returns true if DanishPig instances are equal - /// - /// Instance of DanishPig to be compared - /// Boolean - public bool Equals(DanishPig 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DanishPig + /// + public class DanishPigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DanishPig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new DanishPig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", danishPig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs index d04aa006550..c5e0f5e2ca4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DeprecatedObject /// - public partial class DeprecatedObject : IEquatable, IValidatableObject + public partial class DeprecatedObject : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name - public DeprecatedObject(string name = default) + [JsonConstructor] + public DeprecatedObject(string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for DeprecatedObject and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DeprecatedObject).AreEqual; - } - - /// - /// Returns true if DeprecatedObject instances are equal - /// - /// Instance of DeprecatedObject to be compared - /// Boolean - public bool Equals(DeprecatedObject 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DeprecatedObject + /// + public class DeprecatedObjectJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DeprecatedObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new DeprecatedObject(name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", deprecatedObject.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs index e00bc00421c..ad3da1cfd7d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,16 @@ namespace Org.OpenAPITools.Model /// /// Dog /// - public partial class Dog : Animal, IEquatable + public partial class Dog : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// className (required) + /// className /// color (default to "red") - public Dog(DogAllOf dogAllOf, string className, string color = "red") : base(className, color) + [JsonConstructor] + internal Dog(DogAllOf dogAllOf, string className, string color = "red") : base(className, color) { DogAllOf = dogAllOf; } @@ -57,40 +57,6 @@ namespace Org.OpenAPITools.Model 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 Dog).AreEqual; - } - - /// - /// Returns true if Dog instances are equal - /// - /// Instance of Dog to be compared - /// Boolean - public bool Equals(Dog 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -98,13 +64,6 @@ namespace Org.OpenAPITools.Model /// public class DogJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Dog).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -117,21 +76,26 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader dogAllOfReader = reader; - bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref dogAllOfReader, options, out DogAllOf dogAllOf); + bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out DogAllOf dogAllOf); string className = default; string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -144,6 +108,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -158,6 +124,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", dog.ClassName); + writer.WriteString("color", dog.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DogAllOf.cs index e35252fa263..2e3092d06b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DogAllOf /// - public partial class DogAllOf : IEquatable, IValidatableObject + public partial class DogAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// breed - public DogAllOf(string breed = default) + [JsonConstructor] + public DogAllOf(string breed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (breed == null) + throw new ArgumentNullException("breed is a required property for DogAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Breed = breed; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DogAllOf).AreEqual; - } - - /// - /// Returns true if DogAllOf instances are equal - /// - /// Instance of DogAllOf to be compared - /// Boolean - public bool Equals(DogAllOf 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; - if (this.Breed != null) - { - hashCode = (hashCode * 59) + this.Breed.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DogAllOf + /// + public class DogAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DogAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string breed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "breed": + breed = reader.GetString(); + break; + default: + break; + } + } + } + + return new DogAllOf(breed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DogAllOf dogAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("breed", dogAllOf.Breed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs index 4cb653c55d2..6de00f19504 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,37 @@ namespace Org.OpenAPITools.Model /// /// Drawing /// - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape /// shapeOrNull - /// nullableShape /// shapes - public Drawing(Shape mainShape = default, ShapeOrNull shapeOrNull = default, NullableShape nullableShape = default, List shapes = default) : base() + /// nullableShape + [JsonConstructor] + public Drawing(Shape mainShape, ShapeOrNull shapeOrNull, List shapes, NullableShape nullableShape = default) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mainShape == null) + throw new ArgumentNullException("mainShape is a required property for Drawing and cannot be null."); + + if (shapeOrNull == null) + throw new ArgumentNullException("shapeOrNull is a required property for Drawing and cannot be null."); + + if (shapes == null) + throw new ArgumentNullException("shapes is a required property for Drawing and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + MainShape = mainShape; ShapeOrNull = shapeOrNull; - NullableShape = nullableShape; Shapes = shapes; + NullableShape = nullableShape; } /// @@ -56,18 +71,18 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("shapeOrNull")] public ShapeOrNull ShapeOrNull { get; set; } - /// - /// Gets or Sets NullableShape - /// - [JsonPropertyName("nullableShape")] - public NullableShape NullableShape { get; set; } - /// /// Gets or Sets Shapes /// [JsonPropertyName("shapes")] public List Shapes { get; set; } + /// + /// Gets or Sets NullableShape + /// + [JsonPropertyName("nullableShape")] + public NullableShape NullableShape { get; set; } + /// /// Returns the string presentation of the object /// @@ -79,61 +94,11 @@ namespace Org.OpenAPITools.Model sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); - sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" NullableShape: ").Append(NullableShape).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 Drawing).AreEqual; - } - - /// - /// Returns true if Drawing instances are equal - /// - /// Instance of Drawing to be compared - /// Boolean - public bool Equals(Drawing 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 = base.GetHashCode(); - if (this.MainShape != null) - { - hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); - } - if (this.ShapeOrNull != null) - { - hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); - } - if (this.NullableShape != null) - { - hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); - } - if (this.Shapes != null) - { - hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -145,4 +110,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Drawing + /// + public class DrawingJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Drawing Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Shape mainShape = default; + ShapeOrNull shapeOrNull = default; + List shapes = default; + NullableShape nullableShape = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "mainShape": + mainShape = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapeOrNull": + shapeOrNull = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapes": + shapes = JsonSerializer.Deserialize>(ref reader, options); + break; + case "nullableShape": + nullableShape = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new Drawing(mainShape, shapeOrNull, shapes, nullableShape); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, options); + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, options); + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, options); + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 92f07ad2ee5..c6dcd8b5b24 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,80 @@ namespace Org.OpenAPITools.Model /// /// EnumArrays /// - public partial class EnumArrays : IEquatable, IValidatableObject + public partial class EnumArrays : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) + /// justSymbol + [JsonConstructor] + public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) { - JustSymbol = justSymbol; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justSymbol == null) + throw new ArgumentNullException("justSymbol is a required property for EnumArrays and cannot be null."); + + if (arrayEnum == null) + throw new ArgumentNullException("arrayEnum is a required property for EnumArrays and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayEnum = arrayEnum; + JustSymbol = justSymbol; + } + + /// + /// Defines ArrayEnum + /// + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + Crab = 2 + + } + + /// + /// Returns a ArrayEnumEnum + /// + /// + /// + public static ArrayEnumEnum ArrayEnumEnumFromString(string value) + { + if (value == "fish") + return ArrayEnumEnum.Fish; + + if (value == "crab") + return ArrayEnumEnum.Crab; + + throw new NotImplementedException($"Could not convert value to type ArrayEnumEnum: '{value}'"); + } + + /// + /// Returns equivalent 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}'"); } /// @@ -48,42 +110,54 @@ namespace Org.OpenAPITools.Model /// /// Enum GreaterThanOrEqualTo for value: >= /// - [EnumMember(Value = ">=")] GreaterThanOrEqualTo = 1, /// /// Enum Dollar for value: $ /// - [EnumMember(Value = "$")] Dollar = 2 } + /// + /// Returns a JustSymbolEnum + /// + /// + /// + public static JustSymbolEnum JustSymbolEnumFromString(string value) + { + if (value == ">=") + return JustSymbolEnum.GreaterThanOrEqualTo; + + if (value == "$") + return JustSymbolEnum.Dollar; + + throw new NotImplementedException($"Could not convert value to type JustSymbolEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } - /// - /// Defines ArrayEnum - /// - public enum ArrayEnumEnum - { - /// - /// Enum Fish for value: fish - /// - [EnumMember(Value = "fish")] - Fish = 1, - - /// - /// Enum Crab for value: crab - /// - [EnumMember(Value = "crab")] - Crab = 2 - - } - /// /// Gets or Sets ArrayEnum /// @@ -94,7 +168,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -104,55 +178,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); - sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumArrays).AreEqual; - } - - /// - /// Returns true if EnumArrays instances are equal - /// - /// Instance of EnumArrays to be compared - /// Boolean - public bool Equals(EnumArrays 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) + this.JustSymbol.GetHashCode(); - if (this.ArrayEnum != null) - { - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -164,4 +195,82 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumArrays + /// + public class EnumArraysJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumArrays Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayEnum = default; + EnumArrays.JustSymbolEnum justSymbol = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_enum": + arrayEnum = JsonSerializer.Deserialize>(ref reader, options); + break; + case "just_symbol": + string justSymbolRawValue = reader.GetString(); + justSymbol = EnumArrays.JustSymbolEnumFromString(justSymbolRawValue); + break; + default: + break; + } + } + } + + return new EnumArrays(arrayEnum, justSymbol); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, options); + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); + if (justSymbolRawValue != null) + writer.WriteString("just_symbol", justSymbolRawValue); + else + writer.WriteNull("just_symbol"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs index 390f7f6ea5c..ac9fc84aad6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Abc for value: _abc /// - [EnumMember(Value = "_abc")] Abc = 1, /// /// Enum Efg for value: -efg /// - [EnumMember(Value = "-efg")] Efg = 2, /// /// Enum Xyz for value: (xyz) /// - [EnumMember(Value = "(xyz)")] Xyz = 3 } + + public class EnumClassConverter : JsonConverter + { + public static EnumClass FromString(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + throw new NotImplementedException($"Could not convert value to type EnumClass: '{value}'"); + } + + public static EnumClass? FromStringOrDefault(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override EnumClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + EnumClass? result = EnumClassConverter.FromString(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()); + } + } + + public class EnumClassNullableConverter : JsonConverter + { + /// + /// Returns a EnumClass from the Json object + /// + /// + /// + /// + /// + public override EnumClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + EnumClass? result = EnumClassConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs index 273116bc036..42b07a14075 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,98 +26,64 @@ namespace Org.OpenAPITools.Model /// /// EnumTest /// - public partial class EnumTest : IEquatable, IValidatableObject + public partial class EnumTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// enumStringRequired (required) - /// enumString /// enumInteger /// enumIntegerOnly /// enumNumber - /// outerEnum - /// outerEnumInteger + /// enumString + /// enumStringRequired /// outerEnumDefaultValue + /// outerEnumInteger /// outerEnumIntegerDefaultValue - public EnumTest(EnumStringRequiredEnum enumStringRequired, EnumStringEnum enumString = default, EnumIntegerEnum enumInteger = default, EnumIntegerOnlyEnum enumIntegerOnly = default, EnumNumberEnum enumNumber = default, OuterEnum outerEnum = default, OuterEnumInteger outerEnumInteger = default, OuterEnumDefaultValue outerEnumDefaultValue = default, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = default) + /// outerEnum + [JsonConstructor] + public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (enumString == null) + throw new ArgumentNullException("enumString is a required property for EnumTest and cannot be null."); + if (enumStringRequired == null) throw new ArgumentNullException("enumStringRequired is a required property for EnumTest and cannot be null."); - EnumStringRequired = enumStringRequired; - EnumString = enumString; + if (enumInteger == null) + throw new ArgumentNullException("enumInteger is a required property for EnumTest and cannot be null."); + + if (enumIntegerOnly == null) + throw new ArgumentNullException("enumIntegerOnly is a required property for EnumTest and cannot be null."); + + if (enumNumber == null) + throw new ArgumentNullException("enumNumber is a required property for EnumTest and cannot be null."); + + if (outerEnumInteger == null) + throw new ArgumentNullException("outerEnumInteger is a required property for EnumTest and cannot be null."); + + if (outerEnumDefaultValue == null) + throw new ArgumentNullException("outerEnumDefaultValue is a required property for EnumTest and cannot be null."); + + if (outerEnumIntegerDefaultValue == null) + throw new ArgumentNullException("outerEnumIntegerDefaultValue is a required property for EnumTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + EnumInteger = enumInteger; EnumIntegerOnly = enumIntegerOnly; EnumNumber = enumNumber; - OuterEnum = outerEnum; - OuterEnumInteger = outerEnumInteger; + EnumString = enumString; + EnumStringRequired = enumStringRequired; OuterEnumDefaultValue = outerEnumDefaultValue; + OuterEnumInteger = outerEnumInteger; OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + OuterEnum = outerEnum; } - /// - /// Defines EnumStringRequired - /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumStringRequired - /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } - - /// - /// Defines EnumString - /// - public enum EnumStringEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumString - /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } - /// /// Defines EnumInteger /// @@ -136,6 +101,33 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerEnum + /// + /// + /// + public static EnumIntegerEnum EnumIntegerEnumFromString(string value) + { + if (value == (1).ToString()) + return EnumIntegerEnum.NUMBER_1; + + if (value == (-1).ToString()) + return EnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumInteger /// @@ -159,6 +151,33 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerOnlyEnum + /// + /// + /// + public static EnumIntegerOnlyEnum EnumIntegerOnlyEnumFromString(string value) + { + if (value == (2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_2; + + if (value == (-2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumIntegerOnly /// @@ -173,17 +192,48 @@ namespace Org.OpenAPITools.Model /// /// Enum NUMBER_1_DOT_1 for value: 1.1 /// - [EnumMember(Value = "1.1")] NUMBER_1_DOT_1 = 1, /// /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 /// - [EnumMember(Value = "-1.2")] NUMBER_MINUS_1_DOT_2 = 2 } + /// + /// Returns a EnumNumberEnum + /// + /// + /// + public static EnumNumberEnum EnumNumberEnumFromString(string value) + { + if (value == "1.1") + return EnumNumberEnum.NUMBER_1_DOT_1; + + if (value == "-1.2") + return EnumNumberEnum.NUMBER_MINUS_1_DOT_2; + + throw new NotImplementedException($"Could not convert value to type EnumNumberEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static string 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 /// @@ -191,16 +241,138 @@ namespace Org.OpenAPITools.Model public EnumNumberEnum EnumNumber { get; set; } /// - /// Gets or Sets OuterEnum + /// Defines EnumString /// - [JsonPropertyName("outerEnum")] - public OuterEnum OuterEnum { get; set; } + public enum EnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3 + + } /// - /// Gets or Sets OuterEnumInteger + /// Returns a EnumStringEnum /// - [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + /// + /// + public static EnumStringEnum EnumStringEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringEnum.UPPER; + + if (value == "lower") + return EnumStringEnum.Lower; + + if (value == "") + return EnumStringEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 + + } + + /// + /// Returns a EnumStringRequiredEnum + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringRequiredEnum.UPPER; + + if (value == "lower") + return EnumStringRequiredEnum.Lower; + + if (value == "") + return EnumStringRequiredEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 @@ -208,17 +380,29 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -228,66 +412,19 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); - sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); - sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumTest).AreEqual; - } - - /// - /// Returns true if EnumTest instances are equal - /// - /// Instance of EnumTest to be compared - /// Boolean - public bool Equals(EnumTest 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) + this.EnumStringRequired.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -299,4 +436,143 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumTest + /// + public class EnumTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "enum_integer": + enumInteger = (EnumTest.EnumIntegerEnum) reader.GetInt32(); + break; + case "enum_integer_only": + enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum) reader.GetInt32(); + break; + case "enum_number": + enumNumber = (EnumTest.EnumNumberEnum) reader.GetInt32(); + break; + case "enum_string": + string enumStringRawValue = reader.GetString(); + enumString = EnumTest.EnumStringEnumFromString(enumStringRawValue); + break; + case "enum_string_required": + string enumStringRequiredRawValue = reader.GetString(); + enumStringRequired = EnumTest.EnumStringRequiredEnumFromString(enumStringRequiredRawValue); + break; + case "outerEnumDefaultValue": + string outerEnumDefaultValueRawValue = reader.GetString(); + outerEnumDefaultValue = OuterEnumDefaultValueConverter.FromString(outerEnumDefaultValueRawValue); + break; + case "outerEnumInteger": + string outerEnumIntegerRawValue = reader.GetString(); + outerEnumInteger = OuterEnumIntegerConverter.FromString(outerEnumIntegerRawValue); + break; + case "outerEnumIntegerDefaultValue": + string outerEnumIntegerDefaultValueRawValue = reader.GetString(); + outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValueConverter.FromString(outerEnumIntegerDefaultValueRawValue); + break; + case "outerEnum": + string outerEnumRawValue = reader.GetString(); + outerEnum = OuterEnumConverter.FromStringOrDefault(outerEnumRawValue); + break; + default: + break; + } + } + } + + return new EnumTest(enumInteger, enumIntegerOnly, enumNumber, enumString, enumStringRequired, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue, outerEnum); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("enum_integer", (int)enumTest.EnumInteger); + writer.WriteNumber("enum_integer_only", (int)enumTest.EnumIntegerOnly); + writer.WriteNumber("enum_number", (int)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 = OuterEnumDefaultValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (outerEnumDefaultValueRawValue != null) + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + else + writer.WriteNull("outerEnumDefaultValue"); + var outerEnumIntegerRawValue = OuterEnumIntegerConverter.ToJsonValue(enumTest.OuterEnumInteger); + if (outerEnumIntegerRawValue != null) + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + else + writer.WriteNull("outerEnumInteger"); + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); + if (outerEnumIntegerDefaultValueRawValue != null) + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + else + writer.WriteNull("outerEnumIntegerDefaultValue"); + if (enumTest.OuterEnum == null) + writer.WriteNull("outerEnum"); + var outerEnumRawValue = OuterEnumConverter.ToJsonValue(enumTest.OuterEnum.Value); + if (outerEnumRawValue != null) + writer.WriteString("outerEnum", outerEnumRawValue); + else + writer.WriteNull("outerEnum"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index e6fc1aa4f31..c4d54d076a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// EquilateralTriangle /// - public partial class EquilateralTriangle : IEquatable, IValidatableObject + public partial class EquilateralTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 EquilateralTriangle).AreEqual; - } - - /// - /// Returns true if EquilateralTriangle instances are equal - /// - /// Instance of EquilateralTriangle to be compared - /// Boolean - public bool Equals(EquilateralTriangle 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class EquilateralTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(EquilateralTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs index 86163355eaf..5762b5a5288 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Must be named `File` for test. /// - public partial class File : IEquatable, IValidatableObject + public partial class File : IValidatableObject { /// /// Initializes a new instance of the class. /// /// Test capitalization - public File(string sourceURI = default) + [JsonConstructor] + public File(string sourceURI) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (sourceURI == null) + throw new ArgumentNullException("sourceURI is a required property for File and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + SourceURI = sourceURI; } @@ -49,7 +58,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -64,48 +73,6 @@ namespace Org.OpenAPITools.Model 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 File).AreEqual; - } - - /// - /// Returns true if File instances are equal - /// - /// Instance of File to be compared - /// Boolean - public bool Equals(File 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; - if (this.SourceURI != null) - { - hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -117,4 +84,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type File + /// + public class FileJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override File Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string sourceURI = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "sourceURI": + sourceURI = reader.GetString(); + break; + default: + break; + } + } + } + + return new File(sourceURI); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("sourceURI", file.SourceURI); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 366ead31ee1..d71951f5df6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// FileSchemaTestClass /// - public partial class FileSchemaTestClass : IEquatable, IValidatableObject + public partial class FileSchemaTestClass : IValidatableObject { /// /// Initializes a new instance of the class. /// /// file /// files - public FileSchemaTestClass(File file = default, List files = default) + [JsonConstructor] + public FileSchemaTestClass(File file, List files) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (file == null) + throw new ArgumentNullException("file is a required property for FileSchemaTestClass and cannot be null."); + + if (files == null) + throw new ArgumentNullException("files is a required property for FileSchemaTestClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + File = file; Files = files; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 FileSchemaTestClass).AreEqual; - } - - /// - /// Returns true if FileSchemaTestClass instances are equal - /// - /// Instance of FileSchemaTestClass to be compared - /// Boolean - public bool Equals(FileSchemaTestClass 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; - if (this.File != null) - { - hashCode = (hashCode * 59) + this.File.GetHashCode(); - } - if (this.Files != null) - { - hashCode = (hashCode * 59) + this.Files.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,78 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FileSchemaTestClass + /// + public class FileSchemaTestClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FileSchemaTestClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + File file = default; + List files = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "file": + file = JsonSerializer.Deserialize(ref reader, options); + break; + case "files": + files = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new FileSchemaTestClass(file, files); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, options); + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs index 8be5cfe140b..57810a84fef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Foo /// - public partial class Foo : IEquatable, IValidatableObject + public partial class Foo : IValidatableObject { /// /// Initializes a new instance of the class. /// /// bar (default to "bar") + [JsonConstructor] public Foo(string bar = "bar") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for Foo and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 Foo).AreEqual; - } - - /// - /// Returns true if Foo instances are equal - /// - /// Instance of Foo to be compared - /// Boolean - public bool Equals(Foo 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; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Foo + /// + public class FooJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Foo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + default: + break; + } + } + } + + return new Foo(bar); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", foo.Bar); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index e32cb9257e5..a17a59ac541 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// FooGetDefaultResponse /// - public partial class FooGetDefaultResponse : IEquatable, IValidatableObject + public partial class FooGetDefaultResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _string - public FooGetDefaultResponse(Foo _string = default) + /// stringProperty + [JsonConstructor] + public FooGetDefaultResponse(Foo stringProperty) { - String = _string; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FooGetDefaultResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + StringProperty = stringProperty; } /// - /// Gets or Sets String + /// Gets or Sets StringProperty /// [JsonPropertyName("string")] - public Foo String { get; set; } + public Foo StringProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FooGetDefaultResponse {\n"); - sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).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 FooGetDefaultResponse).AreEqual; - } - - /// - /// Returns true if FooGetDefaultResponse instances are equal - /// - /// Instance of FooGetDefaultResponse to be compared - /// Boolean - public bool Equals(FooGetDefaultResponse 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; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FooGetDefaultResponse + /// + public class FooGetDefaultResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FooGetDefaultResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Foo stringProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "string": + stringProperty = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new FooGetDefaultResponse(stringProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.StringProperty, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs index a767556f460..f3b4b2a9946 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,70 +26,113 @@ namespace Org.OpenAPITools.Model /// /// FormatTest /// - public partial class FormatTest : IEquatable, IValidatableObject + public partial class FormatTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// number (required) - /// _byte (required) - /// date (required) - /// password (required) - /// integer + /// binary + /// byteProperty + /// date + /// dateTime + /// decimalProperty + /// doubleProperty + /// floatProperty /// int32 /// int64 - /// _float - /// _double - /// _decimal - /// _string - /// binary - /// dateTime - /// uuid + /// integer + /// number + /// password /// 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. - public FormatTest(decimal number, byte[] _byte, DateTime date, string password, int integer = default, int int32 = default, long int64 = default, float _float = default, double _double = default, decimal _decimal = default, string _string = default, System.IO.Stream binary = default, DateTime dateTime = default, Guid uuid = default, string patternWithDigits = default, string patternWithDigitsAndDelimiter = default) + /// stringProperty + /// uuid + [JsonConstructor] + public FormatTest(System.IO.Stream binary, byte[] byteProperty, DateTime date, DateTime dateTime, decimal decimalProperty, double doubleProperty, float floatProperty, int int32, long int64, int integer, decimal number, string password, string patternWithDigits, string patternWithDigitsAndDelimiter, string stringProperty, Guid uuid) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (integer == null) + throw new ArgumentNullException("integer is a required property for FormatTest and cannot be null."); + + if (int32 == null) + throw new ArgumentNullException("int32 is a required property for FormatTest and cannot be null."); + + if (int64 == null) + throw new ArgumentNullException("int64 is a required property for FormatTest and cannot be null."); + if (number == null) throw new ArgumentNullException("number is a required property for FormatTest and cannot be null."); - if (_byte == null) - throw new ArgumentNullException("_byte is a required property for FormatTest and cannot be null."); + if (floatProperty == null) + throw new ArgumentNullException("floatProperty is a required property for FormatTest and cannot be null."); + + if (doubleProperty == null) + throw new ArgumentNullException("doubleProperty is a required property for FormatTest and cannot be null."); + + if (decimalProperty == null) + throw new ArgumentNullException("decimalProperty is a required property for FormatTest and cannot be null."); + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FormatTest and cannot be null."); + + if (byteProperty == null) + throw new ArgumentNullException("byteProperty is a required property for FormatTest and cannot be null."); + + if (binary == null) + throw new ArgumentNullException("binary is a required property for FormatTest and cannot be null."); if (date == null) throw new ArgumentNullException("date is a required property for FormatTest and cannot be null."); + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for FormatTest and cannot be null."); + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for FormatTest and cannot be null."); + if (password == null) throw new ArgumentNullException("password is a required property for FormatTest and cannot be null."); - Number = number; - Byte = _byte; + if (patternWithDigits == null) + throw new ArgumentNullException("patternWithDigits is a required property for FormatTest and cannot be null."); + + if (patternWithDigitsAndDelimiter == null) + throw new ArgumentNullException("patternWithDigitsAndDelimiter is a required property for FormatTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Binary = binary; + ByteProperty = byteProperty; Date = date; - Password = password; - Integer = integer; + DateTime = dateTime; + DecimalProperty = decimalProperty; + DoubleProperty = doubleProperty; + FloatProperty = floatProperty; Int32 = int32; Int64 = int64; - Float = _float; - Double = _double; - Decimal = _decimal; - String = _string; - Binary = binary; - DateTime = dateTime; - Uuid = uuid; + Integer = integer; + Number = number; + Password = password; PatternWithDigits = patternWithDigits; PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + StringProperty = stringProperty; + Uuid = uuid; } /// - /// Gets or Sets Number + /// Gets or Sets Binary /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get; set; } /// - /// Gets or Sets Byte + /// Gets or Sets ByteProperty /// [JsonPropertyName("byte")] - public byte[] Byte { get; set; } + public byte[] ByteProperty { get; set; } /// /// Gets or Sets Date @@ -99,16 +141,28 @@ namespace Org.OpenAPITools.Model public DateTime Date { get; set; } /// - /// Gets or Sets Password + /// Gets or Sets DateTime /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonPropertyName("dateTime")] + public DateTime DateTime { get; set; } /// - /// Gets or Sets Integer + /// Gets or Sets DecimalProperty /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonPropertyName("decimal")] + public decimal DecimalProperty { get; set; } + + /// + /// Gets or Sets DoubleProperty + /// + [JsonPropertyName("double")] + public double DoubleProperty { get; set; } + + /// + /// Gets or Sets FloatProperty + /// + [JsonPropertyName("float")] + public float FloatProperty { get; set; } /// /// Gets or Sets Int32 @@ -123,46 +177,22 @@ namespace Org.OpenAPITools.Model public long Int64 { get; set; } /// - /// Gets or Sets Float + /// Gets or Sets Integer /// - [JsonPropertyName("float")] - public float Float { get; set; } + [JsonPropertyName("integer")] + public int Integer { get; set; } /// - /// Gets or Sets Double + /// Gets or Sets Number /// - [JsonPropertyName("double")] - public double Double { get; set; } + [JsonPropertyName("number")] + public decimal Number { get; set; } /// - /// Gets or Sets Decimal + /// Gets or Sets Password /// - [JsonPropertyName("decimal")] - public decimal Decimal { get; set; } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public string String { get; set; } - - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - - /// - /// Gets or Sets DateTime - /// - [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } - - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + [JsonPropertyName("password")] + public string Password { get; set; } /// /// A string that is a 10 digit number. Can have leading zeros. @@ -178,11 +208,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("pattern_with_digits_and_delimiter")] public string PatternWithDigitsAndDelimiter { get; set; } + /// + /// Gets or Sets StringProperty + /// + [JsonPropertyName("string")] + public string StringProperty { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -192,107 +234,26 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" ByteProperty: ").Append(ByteProperty).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" DecimalProperty: ").Append(DecimalProperty).Append("\n"); + sb.Append(" DoubleProperty: ").Append(DoubleProperty).Append("\n"); + sb.Append(" FloatProperty: ").Append(FloatProperty).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" Decimal: ").Append(Decimal).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Uuid: ").Append(Uuid).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(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 FormatTest).AreEqual; - } - - /// - /// Returns true if FormatTest instances are equal - /// - /// Instance of FormatTest to be compared - /// Boolean - public bool Equals(FormatTest 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) + this.Number.GetHashCode(); - if (this.Byte != null) - { - hashCode = (hashCode * 59) + this.Byte.GetHashCode(); - } - if (this.Date != null) - { - hashCode = (hashCode * 59) + this.Date.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Integer.GetHashCode(); - hashCode = (hashCode * 59) + this.Int32.GetHashCode(); - hashCode = (hashCode * 59) + this.Int64.GetHashCode(); - hashCode = (hashCode * 59) + this.Float.GetHashCode(); - hashCode = (hashCode * 59) + this.Double.GetHashCode(); - hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.Binary != null) - { - hashCode = (hashCode * 59) + this.Binary.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.PatternWithDigits != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); - } - if (this.PatternWithDigitsAndDelimiter != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -300,6 +261,54 @@ namespace Org.OpenAPITools.Model /// Validation Result public IEnumerable Validate(ValidationContext validationContext) { + // DoubleProperty (double) maximum + if (this.DoubleProperty > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value less than or equal to 123.4.", new [] { "DoubleProperty" }); + } + + // DoubleProperty (double) minimum + if (this.DoubleProperty < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value greater than or equal to 67.8.", new [] { "DoubleProperty" }); + } + + // FloatProperty (float) maximum + if (this.FloatProperty > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value less than or equal to 987.6.", new [] { "FloatProperty" }); + } + + // FloatProperty (float) minimum + if (this.FloatProperty < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value greater than or equal to 54.3.", new [] { "FloatProperty" }); + } + + // 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) { @@ -324,61 +333,6 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } - // 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" }); - } - - // 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" }); - } - - // Float (float) maximum - if (this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Float (float) minimum - if (this.Float < (float)54.3) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); - } - - // Double (double) maximum - if (this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if (this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\\d{10}$", RegexOptions.CultureInvariant); if (false == regexPatternWithDigits.Match(this.PatternWithDigits).Success) @@ -393,8 +347,162 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } + // StringProperty (string) pattern + Regex regexStringProperty = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexStringProperty.Match(this.StringProperty).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StringProperty, must match a pattern of " + regexStringProperty, new [] { "StringProperty" }); + } + yield break; } } + /// + /// A Json converter for type FormatTest + /// + public class FormatTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FormatTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + System.IO.Stream binary = default; + byte[] byteProperty = default; + DateTime date = default; + DateTime dateTime = default; + decimal decimalProperty = default; + double doubleProperty = default; + float floatProperty = default; + int int32 = default; + long int64 = default; + int integer = default; + decimal number = default; + string password = default; + string patternWithDigits = default; + string patternWithDigitsAndDelimiter = default; + string stringProperty = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "binary": + binary = JsonSerializer.Deserialize(ref reader, options); + break; + case "byte": + byteProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "date": + date = JsonSerializer.Deserialize(ref reader, options); + break; + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "decimal": + decimalProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "double": + doubleProperty = reader.GetDouble(); + break; + case "float": + floatProperty = (float)reader.GetDouble(); + break; + case "int32": + int32 = reader.GetInt32(); + break; + case "int64": + int64 = reader.GetInt64(); + break; + case "integer": + integer = reader.GetInt32(); + break; + case "number": + number = reader.GetInt32(); + break; + case "password": + password = reader.GetString(); + break; + case "pattern_with_digits": + patternWithDigits = reader.GetString(); + break; + case "pattern_with_digits_and_delimiter": + patternWithDigitsAndDelimiter = reader.GetString(); + break; + case "string": + stringProperty = reader.GetString(); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new FormatTest(binary, byteProperty, date, dateTime, decimalProperty, doubleProperty, floatProperty, int32, int64, integer, number, password, patternWithDigits, patternWithDigitsAndDelimiter, stringProperty, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, options); + writer.WritePropertyName("byte"); + JsonSerializer.Serialize(writer, formatTest.ByteProperty, options); + writer.WritePropertyName("date"); + JsonSerializer.Serialize(writer, formatTest.Date, options); + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, formatTest.DateTime, options); + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.DecimalProperty, options); + writer.WriteNumber("double", (int)formatTest.DoubleProperty); + writer.WriteNumber("float", (int)formatTest.FloatProperty); + writer.WriteNumber("int32", (int)formatTest.Int32); + writer.WriteNumber("int64", (int)formatTest.Int64); + writer.WriteNumber("integer", (int)formatTest.Integer); + writer.WriteNumber("number", (int)formatTest.Number); + writer.WriteString("password", formatTest.Password); + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + writer.WriteString("string", formatTest.StringProperty); + writer.WriteString("uuid", formatTest.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs index 95c52488446..3a8b95bb069 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,25 @@ namespace Org.OpenAPITools.Model /// /// Fruit /// - public partial class Fruit : IEquatable, IValidatableObject + public partial class Fruit : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// color - public Fruit(Apple apple, string color = default) + [JsonConstructor] + public Fruit(Apple apple, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = apple; Color = color; } @@ -45,8 +54,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public Fruit(Banana banana, string color = default) + [JsonConstructor] + public Fruit(Banana banana, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Banana = banana; Color = color; } @@ -79,44 +98,6 @@ namespace Org.OpenAPITools.Model 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 Fruit).AreEqual; - } - - /// - /// Returns true if Fruit instances are equal - /// - /// Instance of Fruit to be compared - /// Boolean - public bool Equals(Fruit 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -133,13 +114,6 @@ namespace Org.OpenAPITools.Model /// public class FruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Fruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -152,9 +126,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple apple); @@ -165,10 +141,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -178,6 +157,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -198,6 +179,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", fruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs index f5abf198758..9418bf9a96c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// FruitReq /// - public partial class FruitReq : IEquatable, IValidatableObject + public partial class FruitReq : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public FruitReq(AppleReq appleReq) + [JsonConstructor] + internal FruitReq(AppleReq appleReq) { AppleReq = appleReq; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public FruitReq(BananaReq bananaReq) + [JsonConstructor] + internal FruitReq(BananaReq bananaReq) { BananaReq = bananaReq; } @@ -68,40 +69,6 @@ namespace Org.OpenAPITools.Model 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 FruitReq).AreEqual; - } - - /// - /// Returns true if FruitReq instances are equal - /// - /// Instance of FruitReq to be compared - /// Boolean - public bool Equals(FruitReq 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,13 +85,6 @@ namespace Org.OpenAPITools.Model /// public class FruitReqJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(FruitReq).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -137,9 +97,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReqReader = reader; bool appleReqDeserialized = Client.ClientUtils.TryDeserialize(ref appleReqReader, options, out AppleReq appleReq); @@ -149,16 +111,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +146,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs index 3b4ac358673..cc28f46c42f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,7 +26,7 @@ namespace Org.OpenAPITools.Model /// /// GmFruit /// - public partial class GmFruit : IEquatable, IValidatableObject + public partial class GmFruit : IValidatableObject { /// /// Initializes a new instance of the class. @@ -35,8 +34,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public GmFruit(Apple apple, Banana banana, string color = default) + [JsonConstructor] + public GmFruit(Apple apple, Banana banana, string color) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException("color is a required property for GmFruit and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = Apple; Banana = Banana; Color = color; @@ -70,44 +79,6 @@ namespace Org.OpenAPITools.Model 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 GmFruit).AreEqual; - } - - /// - /// Returns true if GmFruit instances are equal - /// - /// Instance of GmFruit to be compared - /// Boolean - public bool Equals(GmFruit 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +95,6 @@ namespace Org.OpenAPITools.Model /// public class GmFruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(GmFruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,9 +107,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple apple); @@ -156,10 +122,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -169,6 +138,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -183,6 +154,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", gmFruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index c880e6711ef..1557d82e538 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// GrandparentAnimal /// - public partial class GrandparentAnimal : IEquatable, IValidatableObject + public partial class GrandparentAnimal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) + /// petType + [JsonConstructor] public GrandparentAnimal(string petType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (petType == null) throw new ArgumentNullException("petType is a required property for GrandparentAnimal and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + PetType = petType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 GrandparentAnimal).AreEqual; - } - - /// - /// Returns true if GrandparentAnimal instances are equal - /// - /// Instance of GrandparentAnimal to be compared - /// Boolean - public bool Equals(GrandparentAnimal 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; - if (this.PetType != null) - { - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +93,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type GrandparentAnimal + /// + public class GrandparentAnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override GrandparentAnimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "pet_type": + petType = reader.GetString(); + break; + default: + break; + } + } + } + + return new GrandparentAnimal(petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", grandparentAnimal.PetType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 849a4886c31..c0e8044b40b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,8 +33,21 @@ namespace Org.OpenAPITools.Model /// /// bar /// foo - public HasOnlyReadOnly(string bar = default, string foo = default) + [JsonConstructor] + internal HasOnlyReadOnly(string bar, string foo) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for HasOnlyReadOnly and cannot be null."); + + if (foo == null) + throw new ArgumentNullException("foo is a required property for HasOnlyReadOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Foo = foo; } @@ -44,19 +56,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; private set; } + public string Foo { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -102,22 +114,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Foo != null) - { - hashCode = (hashCode * 59) + this.Foo.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -129,4 +132,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HasOnlyReadOnly + /// + public class HasOnlyReadOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HasOnlyReadOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string foo = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "foo": + foo = reader.GetString(); + break; + default: + break; + } + } + } + + return new HasOnlyReadOnly(bar, foo); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", hasOnlyReadOnly.Bar); + writer.WriteString("foo", hasOnlyReadOnly.Foo); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs index f66a3e132f4..2f0e472f639 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,12 +26,13 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class HealthCheckResult : IValidatableObject { /// /// Initializes a new instance of the class. /// /// nullableMessage + [JsonConstructor] public HealthCheckResult(string nullableMessage = default) { NullableMessage = nullableMessage; @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +63,6 @@ namespace Org.OpenAPITools.Model 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 HealthCheckResult).AreEqual; - } - - /// - /// Returns true if HealthCheckResult instances are equal - /// - /// Instance of HealthCheckResult to be compared - /// Boolean - public bool Equals(HealthCheckResult 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; - if (this.NullableMessage != null) - { - hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +74,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HealthCheckResult + /// + public class HealthCheckResultJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HealthCheckResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string nullableMessage = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "NullableMessage": + nullableMessage = reader.GetString(); + break; + default: + break; + } + } + } + + return new HealthCheckResult(nullableMessage); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index d1371b46bf3..45bfcd4f84b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// IsoscelesTriangle /// - public partial class IsoscelesTriangle : IEquatable, IValidatableObject + public partial class IsoscelesTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -61,40 +61,6 @@ namespace Org.OpenAPITools.Model 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 IsoscelesTriangle).AreEqual; - } - - /// - /// Returns true if IsoscelesTriangle instances are equal - /// - /// Instance of IsoscelesTriangle to be compared - /// Boolean - public bool Equals(IsoscelesTriangle 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -111,13 +77,6 @@ namespace Org.OpenAPITools.Model /// public class IsoscelesTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(IsoscelesTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -130,28 +89,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -166,6 +132,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs index 7a3e133f693..654d498a9cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// List /// - public partial class List : IEquatable, IValidatableObject + public partial class List : IValidatableObject { /// /// Initializes a new instance of the class. /// /// _123list - public List(string _123list = default) + [JsonConstructor] + public List(string _123list) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_123list == null) + throw new ArgumentNullException("_123list is a required property for List and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + _123List = _123list; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 List).AreEqual; - } - - /// - /// Returns true if List instances are equal - /// - /// Instance of List to be compared - /// Boolean - public bool Equals(List 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; - if (this._123List != null) - { - hashCode = (hashCode * 59) + this._123List.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type List + /// + public class ListJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string _123list = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "123-list": + _123list = reader.GetString(); + break; + default: + break; + } + } + } + + return new List(_123list); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("123-list", list._123List); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs index f29770cdfe9..87e28b32ff1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Mammal /// - public partial class Mammal : IEquatable, IValidatableObject + public partial class Mammal : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Mammal(Whale whale) + [JsonConstructor] + internal Mammal(Whale whale) { Whale = whale; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Zebra zebra) + [JsonConstructor] + internal Mammal(Zebra zebra) { Zebra = zebra; } @@ -51,7 +52,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Pig pig) + [JsonConstructor] + internal Mammal(Pig pig) { Pig = pig; } @@ -75,7 +77,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -89,44 +91,6 @@ namespace Org.OpenAPITools.Model 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 Mammal).AreEqual; - } - - /// - /// Returns true if Mammal instances are equal - /// - /// Instance of Mammal to be compared - /// Boolean - public bool Equals(Mammal 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -153,13 +117,6 @@ namespace Org.OpenAPITools.Model /// public class MammalJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Mammal).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -172,9 +129,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader whaleReader = reader; bool whaleDeserialized = Client.ClientUtils.TryDeserialize(ref whaleReader, options, out Whale whale); @@ -187,16 +146,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -220,6 +184,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs index 2cf624e2afb..777120531d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,40 @@ namespace Org.OpenAPITools.Model /// /// MapTest /// - public partial class MapTest : IEquatable, IValidatableObject + public partial class MapTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapMapOfString - /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) + /// mapMapOfString + /// mapOfEnumString + [JsonConstructor] + public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) { - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapMapOfString == null) + throw new ArgumentNullException("mapMapOfString is a required property for MapTest and cannot be null."); + + if (mapOfEnumString == null) + throw new ArgumentNullException("mapOfEnumString is a required property for MapTest and cannot be null."); + + if (directMap == null) + throw new ArgumentNullException("directMap is a required property for MapTest and cannot be null."); + + if (indirectMap == null) + throw new ArgumentNullException("indirectMap is a required property for MapTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DirectMap = directMap; IndirectMap = indirectMap; + MapMapOfString = mapMapOfString; + MapOfEnumString = mapOfEnumString; } /// @@ -52,28 +70,47 @@ namespace Org.OpenAPITools.Model /// /// Enum UPPER for value: UPPER /// - [EnumMember(Value = "UPPER")] UPPER = 1, /// /// Enum Lower for value: lower /// - [EnumMember(Value = "lower")] Lower = 2 } /// - /// Gets or Sets MapMapOfString + /// Returns a InnerEnum /// - [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + /// + /// + public static InnerEnum InnerEnumFromString(string value) + { + if (value == "UPPER") + return InnerEnum.UPPER; + + if (value == "lower") + return InnerEnum.Lower; + + throw new NotImplementedException($"Could not convert value to type InnerEnum: '{value}'"); + } /// - /// Gets or Sets MapOfEnumString + /// Returns equivalent json value /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + /// + /// + /// + 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 @@ -87,11 +124,23 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -101,68 +150,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); - sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); - sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as MapTest).AreEqual; - } - - /// - /// Returns true if MapTest instances are equal - /// - /// Instance of MapTest to be compared - /// Boolean - public bool Equals(MapTest 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; - if (this.MapMapOfString != null) - { - hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); - } - if (this.MapOfEnumString != null) - { - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); - } - if (this.DirectMap != null) - { - hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); - } - if (this.IndirectMap != null) - { - hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -174,4 +169,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MapTest + /// + public class MapTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MapTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary directMap = default; + Dictionary indirectMap = default; + Dictionary> mapMapOfString = default; + Dictionary mapOfEnumString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "direct_map": + directMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "indirect_map": + indirectMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_map_of_string": + mapMapOfString = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_of_enum_string": + mapOfEnumString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, options); + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, options); + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, options); + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 68b2ea60b78..4806980e331 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,37 @@ namespace Org.OpenAPITools.Model /// /// MixedPropertiesAndAdditionalPropertiesClass /// - public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid /// dateTime /// map - public MixedPropertiesAndAdditionalPropertiesClass(Guid uuid = default, DateTime dateTime = default, Dictionary map = default) + /// uuid + [JsonConstructor] + public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid) { - Uuid = uuid; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (map == null) + throw new ArgumentNullException("map is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DateTime = dateTime; Map = map; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } - /// /// Gets or Sets DateTime /// @@ -60,11 +69,17 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("map")] public Dictionary Map { get; set; } + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,63 +89,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 MixedPropertiesAndAdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal - /// - /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(MixedPropertiesAndAdditionalPropertiesClass 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Map != null) - { - hashCode = (hashCode * 59) + this.Map.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +107,83 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MixedPropertiesAndAdditionalPropertiesClass + /// + public class MixedPropertiesAndAdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + DateTime dateTime = default; + Dictionary map = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "map": + map = JsonSerializer.Deserialize>(ref reader, options); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.DateTime, options); + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, options); + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs index 6662b2edac4..eca0214cd89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,36 +26,49 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model name starting with number /// - public partial class Model200Response : IEquatable, IValidatableObject + public partial class Model200Response : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// classProperty /// name - /// _class - public Model200Response(int name = default, string _class = default) + [JsonConstructor] + public Model200Response(string classProperty, int name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for Model200Response and cannot be null."); + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for Model200Response and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; Name = name; - Class = _class; } + /// + /// Gets or Sets ClassProperty + /// + [JsonPropertyName("class")] + public string ClassProperty { get; set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] public int Name { get; set; } - /// - /// Gets or Sets Class - /// - [JsonPropertyName("class")] - public string Class { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Class: ").Append(Class).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 Model200Response).AreEqual; - } - - /// - /// Returns true if Model200Response instances are equal - /// - /// Instance of Model200Response to be compared - /// Boolean - public bool Equals(Model200Response 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) + this.Name.GetHashCode(); - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Model200Response + /// + public class Model200ResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Model200Response Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + int name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "class": + classProperty = reader.GetString(); + break; + case "name": + name = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Model200Response(classProperty, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("class", model200Response.ClassProperty); + writer.WriteNumber("name", (int)model200Response.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs index 7bc5c681bbe..dc243ef72f6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// ModelClient /// - public partial class ModelClient : IEquatable, IValidatableObject + public partial class ModelClient : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _client - public ModelClient(string _client = default) + /// clientProperty + [JsonConstructor] + public ModelClient(string clientProperty) { - _Client = _client; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (clientProperty == null) + throw new ArgumentNullException("clientProperty is a required property for ModelClient and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + _ClientProperty = clientProperty; } /// - /// Gets or Sets _Client + /// Gets or Sets _ClientProperty /// [JsonPropertyName("client")] - public string _Client { get; set; } + public string _ClientProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); - sb.Append(" _Client: ").Append(_Client).Append("\n"); + sb.Append(" _ClientProperty: ").Append(_ClientProperty).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 ModelClient).AreEqual; - } - - /// - /// Returns true if ModelClient instances are equal - /// - /// Instance of ModelClient to be compared - /// Boolean - public bool Equals(ModelClient 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; - if (this._Client != null) - { - hashCode = (hashCode * 59) + this._Client.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ModelClient + /// + public class ModelClientJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ModelClient Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string clientProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "client": + clientProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ModelClient(clientProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("client", modelClient._ClientProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs index 95d35d993b2..3e927732b72 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,18 +31,34 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - /// nameProperty (required) - /// snakeCase + /// nameProperty /// property + /// snakeCase /// _123number - public Name(int nameProperty, int snakeCase = default, string property = default, int _123number = default) + [JsonConstructor] + public Name(int nameProperty, string property, int snakeCase, int _123number) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (nameProperty == null) throw new ArgumentNullException("nameProperty is a required property for Name and cannot be null."); + if (snakeCase == null) + throw new ArgumentNullException("snakeCase is a required property for Name and cannot be null."); + + if (property == null) + throw new ArgumentNullException("property is a required property for Name and cannot be null."); + + if (_123number == null) + throw new ArgumentNullException("_123number is a required property for Name and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + NameProperty = nameProperty; - SnakeCase = snakeCase; Property = property; + SnakeCase = snakeCase; _123Number = _123number; } @@ -53,29 +68,29 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("name")] public int NameProperty { get; set; } - /// - /// Gets or Sets SnakeCase - /// - [JsonPropertyName("snake_case")] - public int SnakeCase { get; private 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 _123Number /// [JsonPropertyName("123Number")] - public int _123Number { get; private set; } + public int _123Number { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -86,8 +101,8 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" NameProperty: ").Append(NameProperty).Append("\n"); - sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" _123Number: ").Append(_123Number).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -123,21 +138,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + this.NameProperty.GetHashCode(); - hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); - if (this.Property != null) - { - hashCode = (hashCode * 59) + this.Property.GetHashCode(); - } - hashCode = (hashCode * 59) + this._123Number.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + _123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -149,4 +156,86 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Name + /// + public class NameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Name Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int nameProperty = default; + string property = default; + int snakeCase = default; + int _123number = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + nameProperty = reader.GetInt32(); + break; + case "property": + property = reader.GetString(); + break; + case "snake_case": + snakeCase = reader.GetInt32(); + break; + case "123Number": + _123number = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Name(nameProperty, property, snakeCase, _123number); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("name", (int)name.NameProperty); + writer.WriteString("property", name.Property); + writer.WriteNumber("snake_case", (int)name.SnakeCase); + writer.WriteNumber("123Number", (int)name._123Number); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs index 9bc37488229..0dbf928e051 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,50 +26,75 @@ namespace Org.OpenAPITools.Model /// /// NullableClass /// - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// integerProp - /// numberProp + /// arrayItemsNullable + /// objectItemsNullable + /// arrayAndItemsNullableProp + /// arrayNullableProp /// booleanProp - /// stringProp /// dateProp /// datetimeProp - /// arrayNullableProp - /// arrayAndItemsNullableProp - /// arrayItemsNullable - /// objectNullableProp + /// integerProp + /// numberProp /// objectAndItemsNullableProp - /// objectItemsNullable - public NullableClass(int? integerProp = default, decimal? numberProp = default, bool? booleanProp = default, string stringProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, List arrayNullableProp = default, List arrayAndItemsNullableProp = default, List arrayItemsNullable = default, Dictionary objectNullableProp = default, Dictionary objectAndItemsNullableProp = default, Dictionary objectItemsNullable = default) : base() + /// 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() { - IntegerProp = integerProp; - NumberProp = numberProp; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayItemsNullable == null) + throw new ArgumentNullException("arrayItemsNullable is a required property for NullableClass and cannot be null."); + + if (objectItemsNullable == null) + throw new ArgumentNullException("objectItemsNullable is a required property for NullableClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ArrayItemsNullable = arrayItemsNullable; + ObjectItemsNullable = objectItemsNullable; + ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + ArrayNullableProp = arrayNullableProp; BooleanProp = booleanProp; - StringProp = stringProp; DateProp = dateProp; DatetimeProp = datetimeProp; - ArrayNullableProp = arrayNullableProp; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayItemsNullable = arrayItemsNullable; - ObjectNullableProp = objectNullableProp; + IntegerProp = integerProp; + NumberProp = numberProp; ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectItemsNullable = objectItemsNullable; + ObjectNullableProp = objectNullableProp; + StringProp = stringProp; } /// - /// Gets or Sets IntegerProp + /// Gets or Sets ArrayItemsNullable /// - [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get; set; } /// - /// Gets or Sets NumberProp + /// Gets or Sets ObjectItemsNullable /// - [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + [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 @@ -78,12 +102,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("boolean_prop")] public bool? BooleanProp { get; set; } - /// - /// Gets or Sets StringProp - /// - [JsonPropertyName("string_prop")] - public string StringProp { get; set; } - /// /// Gets or Sets DateProp /// @@ -97,28 +115,16 @@ namespace Org.OpenAPITools.Model public DateTime? DatetimeProp { get; set; } /// - /// Gets or Sets ArrayNullableProp + /// Gets or Sets IntegerProp /// - [JsonPropertyName("array_nullable_prop")] - public List ArrayNullableProp { get; set; } + [JsonPropertyName("integer_prop")] + public int? IntegerProp { get; set; } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Gets or Sets NumberProp /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List ArrayAndItemsNullableProp { get; set; } - - /// - /// Gets or Sets ArrayItemsNullable - /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } - - /// - /// Gets or Sets ObjectNullableProp - /// - [JsonPropertyName("object_nullable_prop")] - public Dictionary ObjectNullableProp { get; set; } + [JsonPropertyName("number_prop")] + public decimal? NumberProp { get; set; } /// /// Gets or Sets ObjectAndItemsNullableProp @@ -127,10 +133,16 @@ namespace Org.OpenAPITools.Model public Dictionary ObjectAndItemsNullableProp { get; set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ObjectNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("object_nullable_prop")] + public Dictionary ObjectNullableProp { get; set; } + + /// + /// Gets or Sets StringProp + /// + [JsonPropertyName("string_prop")] + public string StringProp { get; set; } /// /// Returns the string presentation of the object @@ -141,103 +153,21 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); - sb.Append(" NumberProp: ").Append(NumberProp).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(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); - sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); - sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).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(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" StringProp: ").Append(StringProp).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 NullableClass).AreEqual; - } - - /// - /// Returns true if NullableClass instances are equal - /// - /// Instance of NullableClass to be compared - /// Boolean - public bool Equals(NullableClass 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 = base.GetHashCode(); - if (this.IntegerProp != null) - { - hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); - } - if (this.NumberProp != null) - { - hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); - } - if (this.BooleanProp != null) - { - hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); - } - if (this.StringProp != null) - { - hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); - } - if (this.DateProp != null) - { - hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); - } - if (this.DatetimeProp != null) - { - hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); - } - if (this.ArrayNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); - } - if (this.ArrayAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); - } - if (this.ArrayItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); - } - if (this.ObjectNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); - } - if (this.ObjectAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); - } - if (this.ObjectItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -249,4 +179,145 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NullableClass + /// + public class NullableClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NullableClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_items_nullable": + arrayItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_items_nullable": + objectItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_and_items_nullable_prop": + arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_nullable_prop": + arrayNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "boolean_prop": + booleanProp = reader.GetBoolean(); + break; + case "date_prop": + dateProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "datetime_prop": + datetimeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "integer_prop": + if (reader.TokenType != JsonTokenType.Null) + integerProp = reader.GetInt32(); + break; + case "number_prop": + if (reader.TokenType != JsonTokenType.Null) + numberProp = reader.GetInt32(); + break; + case "object_and_items_nullable_prop": + objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_nullable_prop": + objectNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "string_prop": + stringProp = reader.GetString(); + break; + default: + break; + } + } + } + + return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, options); + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, options); + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, options); + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, options); + if (nullableClass.BooleanProp != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); + else + writer.WriteNull("boolean_prop"); + writer.WritePropertyName("date_prop"); + JsonSerializer.Serialize(writer, nullableClass.DateProp, options); + writer.WritePropertyName("datetime_prop"); + JsonSerializer.Serialize(writer, nullableClass.DatetimeProp, options); + if (nullableClass.IntegerProp != null) + writer.WriteNumber("integer_prop", (int)nullableClass.IntegerProp.Value); + else + writer.WriteNull("integer_prop"); + if (nullableClass.NumberProp != null) + writer.WriteNumber("number_prop", (int)nullableClass.NumberProp.Value); + else + writer.WriteNull("number_prop"); + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, options); + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, options); + writer.WriteString("string_prop", nullableClass.StringProp); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs index 5ef1763454a..bcd4b60c1df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class NullableShape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public NullableShape(Triangle triangle) + [JsonConstructor] + internal NullableShape(Triangle triangle) { Triangle = triangle; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public NullableShape(Quadrilateral quadrilateral) + [JsonConstructor] + internal NullableShape(Quadrilateral quadrilateral) { Quadrilateral = quadrilateral; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 NullableShape).AreEqual; - } - - /// - /// Returns true if NullableShape instances are equal - /// - /// Instance of NullableShape to be compared - /// Boolean - public bool Equals(NullableShape 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class NullableShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(NullableShape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs index 64f6395b603..035a084d727 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// NumberOnly /// - public partial class NumberOnly : IEquatable, IValidatableObject + public partial class NumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// justNumber - public NumberOnly(decimal justNumber = default) + [JsonConstructor] + public NumberOnly(decimal justNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justNumber == null) + throw new ArgumentNullException("justNumber is a required property for NumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + JustNumber = justNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 NumberOnly).AreEqual; - } - - /// - /// Returns true if NumberOnly instances are equal - /// - /// Instance of NumberOnly to be compared - /// Boolean - public bool Equals(NumberOnly 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) + this.JustNumber.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NumberOnly + /// + public class NumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal justNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "JustNumber": + justNumber = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new NumberOnly(justNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("JustNumber", (int)numberOnly.JustNumber); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 817af80674c..26f0d3f5fa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,43 +26,42 @@ namespace Org.OpenAPITools.Model /// /// ObjectWithDeprecatedFields /// - public partial class ObjectWithDeprecatedFields : IEquatable, IValidatableObject + public partial class ObjectWithDeprecatedFields : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid - /// id - /// deprecatedRef /// bars - public ObjectWithDeprecatedFields(string uuid = default, decimal id = default, DeprecatedObject deprecatedRef = default, List bars = default) + /// deprecatedRef + /// id + /// uuid + [JsonConstructor] + public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) { - Uuid = uuid; - Id = id; - DeprecatedRef = deprecatedRef; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (id == null) + throw new ArgumentNullException("id is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (deprecatedRef == null) + throw new ArgumentNullException("deprecatedRef is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (bars == null) + throw new ArgumentNullException("bars is a required property for ObjectWithDeprecatedFields and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bars = bars; + DeprecatedRef = deprecatedRef; + Id = id; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public string Uuid { get; set; } - - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - [Obsolete] - public decimal Id { get; set; } - - /// - /// Gets or Sets DeprecatedRef - /// - [JsonPropertyName("deprecatedRef")] - [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } - /// /// Gets or Sets Bars /// @@ -71,11 +69,31 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -85,65 +103,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" DeprecatedRef: ").Append(DeprecatedRef).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ObjectWithDeprecatedFields).AreEqual; - } - - /// - /// Returns true if ObjectWithDeprecatedFields instances are equal - /// - /// Instance of ObjectWithDeprecatedFields to be compared - /// Boolean - public bool Equals(ObjectWithDeprecatedFields 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.DeprecatedRef != null) - { - hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); - } - if (this.Bars != null) - { - hashCode = (hashCode * 59) + this.Bars.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -155,4 +122,88 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ObjectWithDeprecatedFields + /// + public class ObjectWithDeprecatedFieldsJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List bars = default; + DeprecatedObject deprecatedRef = default; + decimal id = default; + string uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bars": + bars = JsonSerializer.Deserialize>(ref reader, options); + break; + case "deprecatedRef": + deprecatedRef = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt32(); + break; + case "uuid": + uuid = reader.GetString(); + break; + default: + break; + } + } + } + + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, options); + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, options); + writer.WriteNumber("id", (int)objectWithDeprecatedFields.Id); + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs index 2fef14a9c59..62777359e73 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,7 +26,7 @@ namespace Org.OpenAPITools.Model /// /// Order /// - public partial class Order : IEquatable, IValidatableObject + public partial class Order : IValidatableObject { /// /// Initializes a new instance of the class. @@ -38,8 +37,33 @@ namespace Org.OpenAPITools.Model /// shipDate /// Order Status /// complete (default to false) - public Order(long id = default, long petId = default, int quantity = default, DateTime shipDate = default, StatusEnum status = default, bool complete = false) + [JsonConstructor] + public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Order and cannot be null."); + + if (petId == null) + throw new ArgumentNullException("petId is a required property for Order and cannot be null."); + + if (quantity == null) + throw new ArgumentNullException("quantity is a required property for Order and cannot be null."); + + if (shipDate == null) + throw new ArgumentNullException("shipDate is a required property for Order and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Order and cannot be null."); + + if (complete == null) + throw new ArgumentNullException("complete is a required property for Order and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; PetId = petId; Quantity = quantity; @@ -57,23 +81,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "placed") + return StatusEnum.Placed; + + if (value == "approved") + return StatusEnum.Approved; + + if (value == "delivered") + return StatusEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -115,7 +175,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -135,53 +195,6 @@ namespace Org.OpenAPITools.Model 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 Order).AreEqual; - } - - /// - /// Returns true if Order instances are equal - /// - /// Instance of Order to be compared - /// Boolean - public bool Equals(Order 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) + this.Id.GetHashCode(); - hashCode = (hashCode * 59) + this.PetId.GetHashCode(); - hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); - if (this.ShipDate != null) - { - hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - hashCode = (hashCode * 59) + this.Complete.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -193,4 +206,102 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Order + /// + public class OrderJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Order Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + long petId = default; + int quantity = default; + DateTime shipDate = default; + Order.StatusEnum status = default; + bool complete = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "petId": + petId = reader.GetInt64(); + break; + case "quantity": + quantity = reader.GetInt32(); + break; + case "shipDate": + shipDate = JsonSerializer.Deserialize(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Order.StatusEnumFromString(statusRawValue); + break; + case "complete": + complete = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Order(id, petId, quantity, shipDate, status, complete); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)order.Id); + writer.WriteNumber("petId", (int)order.PetId); + writer.WriteNumber("quantity", (int)order.Quantity); + writer.WritePropertyName("shipDate"); + JsonSerializer.Serialize(writer, order.ShipDate, options); + var statusRawValue = Order.StatusEnumToJsonValue(order.Status); + if (statusRawValue != null) + writer.WriteString("status", statusRawValue); + else + writer.WriteNull("status"); + writer.WriteBoolean("complete", order.Complete); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs index 390b308657e..13f5f05b588 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,43 @@ namespace Org.OpenAPITools.Model /// /// OuterComposite /// - public partial class OuterComposite : IEquatable, IValidatableObject + public partial class OuterComposite : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// myBoolean /// myNumber /// myString - /// myBoolean - public OuterComposite(decimal myNumber = default, string myString = default, bool myBoolean = default) + [JsonConstructor] + public OuterComposite(bool myBoolean, decimal myNumber, string myString) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (myNumber == null) + throw new ArgumentNullException("myNumber is a required property for OuterComposite and cannot be null."); + + if (myString == null) + throw new ArgumentNullException("myString is a required property for OuterComposite and cannot be null."); + + if (myBoolean == null) + throw new ArgumentNullException("myBoolean is a required property for OuterComposite and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + MyBoolean = myBoolean; MyNumber = myNumber; MyString = myString; - MyBoolean = myBoolean; } + /// + /// Gets or Sets MyBoolean + /// + [JsonPropertyName("my_boolean")] + public bool MyBoolean { get; set; } + /// /// Gets or Sets MyNumber /// @@ -54,17 +75,11 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("my_string")] public string MyString { get; set; } - /// - /// Gets or Sets MyBoolean - /// - [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,57 +89,13 @@ namespace Org.OpenAPITools.Model { 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(" MyBoolean: ").Append(MyBoolean).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 OuterComposite).AreEqual; - } - - /// - /// Returns true if OuterComposite instances are equal - /// - /// Instance of OuterComposite to be compared - /// Boolean - public bool Equals(OuterComposite 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) + this.MyNumber.GetHashCode(); - if (this.MyString != null) - { - hashCode = (hashCode * 59) + this.MyString.GetHashCode(); - } - hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -136,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type OuterComposite + /// + public class OuterCompositeJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override OuterComposite Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool myBoolean = default; + decimal myNumber = default; + string myString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "my_boolean": + myBoolean = reader.GetBoolean(); + break; + case "my_number": + myNumber = reader.GetInt32(); + break; + case "my_string": + myString = reader.GetString(); + break; + default: + break; + } + } + } + + return new OuterComposite(myBoolean, myNumber, myString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); + writer.WriteNumber("my_number", (int)outerComposite.MyNumber); + writer.WriteString("my_string", outerComposite.MyString); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs index 8496c413326..31e3049659b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumConverter : JsonConverter + { + public static OuterEnum FromString(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnum: '{value}'"); + } + + public static OuterEnum? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnum? result = OuterEnumConverter.FromString(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()); + } + } + + public class OuterEnumNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnum from the Json object + /// + /// + /// + /// + /// + public override OuterEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnum? result = OuterEnumConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index b0f9d099e27..d3f7db5b4fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumDefaultValueConverter : JsonConverter + { + public static OuterEnumDefaultValue FromString(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnumDefaultValue: '{value}'"); + } + + public static OuterEnumDefaultValue? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 56069346c2e..e704048b8c3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -45,4 +44,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerConverter : JsonConverter + { + public static OuterEnumInteger FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumInteger: '{value}'"); + } + + public static OuterEnumInteger? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumInteger value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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()); + } + } + + public class OuterEnumIntegerNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumInteger from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index e80f88f51f3..8e559a7975b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -45,4 +44,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerDefaultValueConverter : JsonConverter + { + public static OuterEnumIntegerDefaultValue FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumIntegerDefaultValue: '{value}'"); + } + + public static OuterEnumIntegerDefaultValue? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumIntegerDefaultValue value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumIntegerDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumIntegerDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs index 244b3b93840..fa0bfd0120e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// ParentPet /// - public partial class ParentPet : GrandparentAnimal, IEquatable + public partial class ParentPet : GrandparentAnimal, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) - public ParentPet(string petType) : base(petType) + /// petType + [JsonConstructor] + internal ParentPet(string petType) : base(petType) { } @@ -49,40 +49,6 @@ namespace Org.OpenAPITools.Model 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 ParentPet).AreEqual; - } - - /// - /// Returns true if ParentPet instances are equal - /// - /// Instance of ParentPet to be compared - /// Boolean - public bool Equals(ParentPet 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -90,13 +56,6 @@ namespace Org.OpenAPITools.Model /// public class ParentPetJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ParentPet).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -109,17 +68,22 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -129,6 +93,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -143,6 +109,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", parentPet.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs index 0091def60e5..ad0e1587799 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,31 +26,50 @@ namespace Org.OpenAPITools.Model /// /// Pet /// - public partial class Pet : IEquatable, IValidatableObject + public partial class Pet : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) - /// photoUrls (required) - /// id /// category - /// tags + /// id + /// name + /// photoUrls /// pet status in the store - public Pet(string name, List photoUrls, long id = default, Category category = default, List tags = default, StatusEnum status = default) + /// tags + [JsonConstructor] + public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Pet and cannot be null."); + + if (category == null) + throw new ArgumentNullException("category is a required property for Pet and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Pet and cannot be null."); if (photoUrls == null) throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null."); + if (tags == null) + throw new ArgumentNullException("tags is a required property for Pet and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Pet and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Category = category; + Id = id; Name = name; PhotoUrls = photoUrls; - Id = id; - Category = category; - Tags = tags; Status = status; + Tags = tags; } /// @@ -63,23 +81,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Available for value: available /// - [EnumMember(Value = "available")] Available = 1, /// /// Enum Pending for value: pending /// - [EnumMember(Value = "pending")] Pending = 2, /// /// Enum Sold for value: sold /// - [EnumMember(Value = "sold")] Sold = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "available") + return StatusEnum.Available; + + if (value == "pending") + return StatusEnum.Pending; + + if (value == "sold") + return StatusEnum.Sold; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -87,6 +141,18 @@ namespace Org.OpenAPITools.Model [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 /// @@ -99,18 +165,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("photoUrls")] public List PhotoUrls { get; set; } - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - public long Id { get; set; } - - /// - /// Gets or Sets Category - /// - [JsonPropertyName("category")] - public Category Category { get; set; } - /// /// Gets or Sets Tags /// @@ -121,7 +175,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -131,72 +185,16 @@ namespace Org.OpenAPITools.Model { 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(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Tags: ").Append(Tags).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Pet).AreEqual; - } - - /// - /// Returns true if Pet instances are equal - /// - /// Instance of Pet to be compared - /// Boolean - public bool Equals(Pet 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.PhotoUrls != null) - { - hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.Category != null) - { - hashCode = (hashCode * 59) + this.Category.GetHashCode(); - } - if (this.Tags != null) - { - hashCode = (hashCode * 59) + this.Tags.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -208,4 +206,104 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Pet + /// + public class PetJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Pet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Category category = default; + long id = default; + string name = default; + List photoUrls = default; + Pet.StatusEnum status = default; + List tags = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "category": + category = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + case "photoUrls": + photoUrls = JsonSerializer.Deserialize>(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Pet.StatusEnumFromString(statusRawValue); + break; + case "tags": + tags = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new Pet(category, id, name, photoUrls, status, tags); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, options); + writer.WriteNumber("id", (int)pet.Id); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); + JsonSerializer.Serialize(writer, pet.PhotoUrls, options); + 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, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs index 4eb947b0140..b2292d1331e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Pig /// - public partial class Pig : IEquatable, IValidatableObject + public partial class Pig : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Pig(BasquePig basquePig) + [JsonConstructor] + internal Pig(BasquePig basquePig) { BasquePig = basquePig; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Pig(DanishPig danishPig) + [JsonConstructor] + internal Pig(DanishPig danishPig) { DanishPig = danishPig; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 Pig).AreEqual; - } - - /// - /// Returns true if Pig instances are equal - /// - /// Instance of Pig to be compared - /// Boolean - public bool Equals(Pig 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class PigJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Pig).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader basquePigReader = reader; bool basquePigDeserialized = Client.ClientUtils.TryDeserialize(ref basquePigReader, options, out BasquePig basquePig); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index 1152b4e63f4..e7a03145456 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// PolymorphicProperty /// - public partial class PolymorphicProperty : IEquatable, IValidatableObject + public partial class PolymorphicProperty : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(bool _bool) + [JsonConstructor] + internal PolymorphicProperty(bool _bool) { Bool = _bool; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(string _string) + [JsonConstructor] + internal PolymorphicProperty(string _string) { String = _string; } @@ -51,7 +52,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(Object _object) + [JsonConstructor] + internal PolymorphicProperty(Object _object) { Object = _object; } @@ -60,7 +62,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(List liststring) + [JsonConstructor] + internal PolymorphicProperty(List liststring) { Liststring = liststring; } @@ -89,7 +92,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -103,44 +106,6 @@ namespace Org.OpenAPITools.Model 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 PolymorphicProperty).AreEqual; - } - - /// - /// Returns true if PolymorphicProperty instances are equal - /// - /// Instance of PolymorphicProperty to be compared - /// Boolean - public bool Equals(PolymorphicProperty 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -157,13 +122,6 @@ namespace Org.OpenAPITools.Model /// public class PolymorphicPropertyJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(PolymorphicProperty).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -176,9 +134,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader _boolReader = reader; bool _boolDeserialized = Client.ClientUtils.TryDeserialize(ref _boolReader, options, out bool _bool); @@ -194,16 +154,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -230,6 +195,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs index 47e72d44ab6..d1dcd22b8e3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Quadrilateral /// - public partial class Quadrilateral : IEquatable, IValidatableObject + public partial class Quadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) + [JsonConstructor] + internal Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) { SimpleQuadrilateral = simpleQuadrilateral; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Quadrilateral(ComplexQuadrilateral complexQuadrilateral) + [JsonConstructor] + internal Quadrilateral(ComplexQuadrilateral complexQuadrilateral) { ComplexQuadrilateral = complexQuadrilateral; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 Quadrilateral).AreEqual; - } - - /// - /// Returns true if Quadrilateral instances are equal - /// - /// Instance of Quadrilateral to be compared - /// Boolean - public bool Equals(Quadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class QuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Quadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader simpleQuadrilateralReader = reader; bool simpleQuadrilateralDeserialized = Client.ClientUtils.TryDeserialize(ref simpleQuadrilateralReader, options, out SimpleQuadrilateral simpleQuadrilateral); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 046b9050ba0..6faf1ddd505 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// QuadrilateralInterface /// - public partial class QuadrilateralInterface : IEquatable, IValidatableObject + public partial class QuadrilateralInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public QuadrilateralInterface(string quadrilateralType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) throw new ArgumentNullException("quadrilateralType is a required property for QuadrilateralInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + QuadrilateralType = quadrilateralType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 QuadrilateralInterface).AreEqual; - } - - /// - /// Returns true if QuadrilateralInterface instances are equal - /// - /// Instance of QuadrilateralInterface to be compared - /// Boolean - public bool Equals(QuadrilateralInterface 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type QuadrilateralInterface + /// + public class QuadrilateralInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override QuadrilateralInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string quadrilateralType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "quadrilateralType": + quadrilateralType = reader.GetString(); + break; + default: + break; + } + } + } + + return new QuadrilateralInterface(quadrilateralType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 3589a97ed6c..d81d94a35fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,8 +33,21 @@ namespace Org.OpenAPITools.Model /// /// bar /// baz - public ReadOnlyFirst(string bar = default, string baz = default) + [JsonConstructor] + public ReadOnlyFirst(string bar, string baz) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for ReadOnlyFirst and cannot be null."); + + if (baz == null) + throw new ArgumentNullException("baz is a required property for ReadOnlyFirst and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Baz = baz; } @@ -44,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Baz @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -102,22 +114,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Baz != null) - { - hashCode = (hashCode * 59) + this.Baz.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -129,4 +131,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ReadOnlyFirst + /// + public class ReadOnlyFirstJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ReadOnlyFirst Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string baz = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "baz": + baz = reader.GetString(); + break; + default: + break; + } + } + } + + return new ReadOnlyFirst(bar, baz); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", readOnlyFirst.Bar); + writer.WriteString("baz", readOnlyFirst.Baz); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs index 2b73710ad81..b560dc903b9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Model for testing reserved words /// - public partial class Return : IEquatable, IValidatableObject + public partial class Return : IValidatableObject { /// /// Initializes a new instance of the class. /// /// returnProperty - public Return(int returnProperty = default) + [JsonConstructor] + public Return(int returnProperty) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (returnProperty == null) + throw new ArgumentNullException("returnProperty is a required property for Return and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ReturnProperty = returnProperty; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 Return).AreEqual; - } - - /// - /// Returns true if Return instances are equal - /// - /// Instance of Return to be compared - /// Boolean - public bool Equals(Return 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) + this.ReturnProperty.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Return + /// + public class ReturnJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Return Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int returnProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "return": + returnProperty = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Return(returnProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Return _return, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("return", (int)_return.ReturnProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 72568e1e01b..7654a4f8a09 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ScaleneTriangle /// - public partial class ScaleneTriangle : IEquatable, IValidatableObject + public partial class ScaleneTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 ScaleneTriangle).AreEqual; - } - - /// - /// Returns true if ScaleneTriangle instances are equal - /// - /// Instance of ScaleneTriangle to be compared - /// Boolean - public bool Equals(ScaleneTriangle 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class ScaleneTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ScaleneTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs index e2cf8fb7cce..7412f32e61d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Shape /// - public partial class Shape : IEquatable, IValidatableObject + public partial class Shape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -47,11 +53,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -77,7 +90,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -92,48 +105,6 @@ namespace Org.OpenAPITools.Model 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 Shape).AreEqual; - } - - /// - /// Returns true if Shape instances are equal - /// - /// Instance of Shape to be compared - /// Boolean - public bool Equals(Shape 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -160,13 +131,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Shape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -179,9 +143,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -192,10 +158,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -205,6 +174,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -225,6 +196,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shape.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index 5d0ab8ec9c7..b6a27e5efcc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ShapeInterface /// - public partial class ShapeInterface : IEquatable, IValidatableObject + public partial class ShapeInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// shapeType (required) + /// shapeType + [JsonConstructor] public ShapeInterface(string shapeType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) throw new ArgumentNullException("shapeType is a required property for ShapeInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ShapeType = shapeType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ShapeInterface).AreEqual; - } - - /// - /// Returns true if ShapeInterface instances are equal - /// - /// Instance of ShapeInterface to be compared - /// Boolean - public bool Equals(ShapeInterface 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ShapeInterface + /// + public class ShapeInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ShapeInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string shapeType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "shapeType": + shapeType = reader.GetString(); + break; + default: + break; + } + } + } + + return new ShapeInterface(shapeType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", shapeInterface.ShapeType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 375f4d49076..64971919ee7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. /// - public partial class ShapeOrNull : IEquatable, IValidatableObject + public partial class ShapeOrNull : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -47,11 +53,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -77,7 +90,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -92,48 +105,6 @@ namespace Org.OpenAPITools.Model 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 ShapeOrNull).AreEqual; - } - - /// - /// Returns true if ShapeOrNull instances are equal - /// - /// Instance of ShapeOrNull to be compared - /// Boolean - public bool Equals(ShapeOrNull 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -160,13 +131,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeOrNullJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ShapeOrNull).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -179,9 +143,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -192,10 +158,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -205,6 +174,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -225,6 +196,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shapeOrNull.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index ee6d8ef1823..feb4017722a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// SimpleQuadrilateral /// - public partial class SimpleQuadrilateral : IEquatable, IValidatableObject + public partial class SimpleQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 SimpleQuadrilateral).AreEqual; - } - - /// - /// Returns true if SimpleQuadrilateral instances are equal - /// - /// Instance of SimpleQuadrilateral to be compared - /// Boolean - public bool Equals(SimpleQuadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class SimpleQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(SimpleQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs index 35fc0efd1c5..db141494908 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,24 +26,31 @@ namespace Org.OpenAPITools.Model /// /// SpecialModelName /// - public partial class SpecialModelName : IEquatable, IValidatableObject + public partial class SpecialModelName : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// specialPropertyName /// specialModelNameProperty - public SpecialModelName(long specialPropertyName = default, string specialModelNameProperty = default) + /// specialPropertyName + [JsonConstructor] + public SpecialModelName(string specialModelNameProperty, long specialPropertyName) { - SpecialPropertyName = specialPropertyName; - SpecialModelNameProperty = specialModelNameProperty; - } +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - /// - /// Gets or Sets SpecialPropertyName - /// - [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + if (specialPropertyName == null) + throw new ArgumentNullException("specialPropertyName is a required property for SpecialModelName and cannot be null."); + + if (specialModelNameProperty == null) + throw new ArgumentNullException("specialModelNameProperty is a required property for SpecialModelName and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + SpecialModelNameProperty = specialModelNameProperty; + SpecialPropertyName = specialPropertyName; + } /// /// Gets or Sets SpecialModelNameProperty @@ -52,11 +58,17 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("_special_model.name_")] public string SpecialModelNameProperty { 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); - sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" SpecialModelNameProperty: ").Append(SpecialModelNameProperty).Append("\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).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 SpecialModelName).AreEqual; - } - - /// - /// Returns true if SpecialModelName instances are equal - /// - /// Instance of SpecialModelName to be compared - /// Boolean - public bool Equals(SpecialModelName 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) + this.SpecialPropertyName.GetHashCode(); - if (this.SpecialModelNameProperty != null) - { - hashCode = (hashCode * 59) + this.SpecialModelNameProperty.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type SpecialModelName + /// + public class SpecialModelNameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override SpecialModelName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string specialModelNameProperty = default; + long specialPropertyName = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_special_model.name_": + specialModelNameProperty = reader.GetString(); + break; + case "$special[property.name]": + specialPropertyName = reader.GetInt64(); + break; + default: + break; + } + } + } + + return new SpecialModelName(specialModelNameProperty, specialPropertyName); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_special_model.name_", specialModelName.SpecialModelNameProperty); + writer.WriteNumber("$special[property.name]", (int)specialModelName.SpecialPropertyName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs index fcc38c0b3ac..51a80012fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Tag /// - public partial class Tag : IEquatable, IValidatableObject + public partial class Tag : IValidatableObject { /// /// Initializes a new instance of the class. /// /// id /// name - public Tag(long id = default, string name = default) + [JsonConstructor] + public Tag(long id, string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Tag and cannot be null."); + + if (name == null) + throw new ArgumentNullException("name is a required property for Tag and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; Name = name; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,49 +84,6 @@ namespace Org.OpenAPITools.Model 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 Tag).AreEqual; - } - - /// - /// Returns true if Tag instances are equal - /// - /// Instance of Tag to be compared - /// Boolean - public bool Equals(Tag 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) + this.Id.GetHashCode(); - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Tag + /// + public class TagJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Tag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Tag(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)tag.Id); + writer.WriteString("name", tag.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs index f799b7c43bb..6f5eae3cca6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Triangle /// - public partial class Triangle : IEquatable, IValidatableObject + public partial class Triangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(EquilateralTriangle equilateralTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' EquilateralTriangle = equilateralTriangle; ShapeType = shapeType; @@ -52,15 +58,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(IsoscelesTriangle isoscelesTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' IsoscelesTriangle = isoscelesTriangle; ShapeType = shapeType; @@ -71,15 +84,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(ScaleneTriangle scaleneTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' ScaleneTriangle = scaleneTriangle; ShapeType = shapeType; @@ -117,7 +137,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -133,52 +153,6 @@ namespace Org.OpenAPITools.Model 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 Triangle).AreEqual; - } - - /// - /// Returns true if Triangle instances are equal - /// - /// Instance of Triangle to be compared - /// Boolean - public bool Equals(Triangle 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -205,13 +179,6 @@ namespace Org.OpenAPITools.Model /// public class TriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Triangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -224,9 +191,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader equilateralTriangleReader = reader; bool equilateralTriangleDeserialized = Client.ClientUtils.TryDeserialize(ref equilateralTriangleReader, options, out EquilateralTriangle equilateralTriangle); @@ -241,10 +210,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -257,6 +229,8 @@ namespace Org.OpenAPITools.Model case "triangleType": triangleType = reader.GetString(); break; + default: + break; } } } @@ -280,6 +254,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", triangle.ShapeType); + writer.WriteString("triangleType", triangle.TriangleType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index f7b06bf05a9..882d2b9e429 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// TriangleInterface /// - public partial class TriangleInterface : IEquatable, IValidatableObject + public partial class TriangleInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// triangleType (required) + /// triangleType + [JsonConstructor] public TriangleInterface(string triangleType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (triangleType == null) throw new ArgumentNullException("triangleType is a required property for TriangleInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + TriangleType = triangleType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 TriangleInterface).AreEqual; - } - - /// - /// Returns true if TriangleInterface instances are equal - /// - /// Instance of TriangleInterface to be compared - /// Boolean - public bool Equals(TriangleInterface 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; - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type TriangleInterface + /// + public class TriangleInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override TriangleInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string triangleType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "triangleType": + triangleType = reader.GetString(); + break; + default: + break; + } + } + } + + return new TriangleInterface(triangleType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("triangleType", triangleInterface.TriangleType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs index 38a79e975db..a92270295ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,50 +26,78 @@ namespace Org.OpenAPITools.Model /// /// User /// - public partial class User : IEquatable, IValidatableObject + public partial class User : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// id - /// username - /// firstName - /// lastName /// 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 - /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// 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. - public User(long id = default, string username = default, string firstName = default, string lastName = default, string email = default, string password = default, string phone = default, int userStatus = default, Object objectWithNoDeclaredProps = default, Object objectWithNoDeclaredPropsNullable = default, Object anyTypeProp = default, Object anyTypePropNullable = default) + /// 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) { - Id = id; - Username = username; - FirstName = firstName; - LastName = lastName; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for User and cannot be null."); + + if (username == null) + throw new ArgumentNullException("username is a required property for User and cannot be null."); + + if (firstName == null) + throw new ArgumentNullException("firstName is a required property for User and cannot be null."); + + if (lastName == null) + throw new ArgumentNullException("lastName is a required property for User and cannot be null."); + + if (email == null) + throw new ArgumentNullException("email is a required property for User and cannot be null."); + + if (password == null) + throw new ArgumentNullException("password is a required property for User and cannot be null."); + + if (phone == null) + throw new ArgumentNullException("phone is a required property for User and cannot be null."); + + if (userStatus == null) + throw new ArgumentNullException("userStatus is a required property for User and cannot be null."); + + if (objectWithNoDeclaredProps == null) + throw new ArgumentNullException("objectWithNoDeclaredProps is a required property for User and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Email = email; + FirstName = firstName; + Id = id; + LastName = lastName; + ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; Password = password; Phone = phone; UserStatus = userStatus; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + Username = username; AnyTypeProp = anyTypeProp; AnyTypePropNullable = anyTypePropNullable; + ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; } /// - /// Gets or Sets Id + /// Gets or Sets Email /// - [JsonPropertyName("id")] - public long Id { get; set; } - - /// - /// Gets or Sets Username - /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonPropertyName("email")] + public string Email { get; set; } /// /// Gets or Sets FirstName @@ -78,6 +105,12 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("firstName")] public string FirstName { get; set; } + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + /// /// Gets or Sets LastName /// @@ -85,10 +118,11 @@ namespace Org.OpenAPITools.Model public string LastName { get; set; } /// - /// Gets or Sets Email + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// - [JsonPropertyName("email")] - public string Email { get; set; } + /// 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 @@ -110,18 +144,10 @@ namespace Org.OpenAPITools.Model public int UserStatus { get; set; } /// - /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// Gets or Sets Username /// - /// 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; } - - /// - /// 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; } + [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 @@ -137,11 +163,18 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -151,102 +184,22 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" FirstName: ").Append(FirstName).Append("\n"); - sb.Append(" LastName: ").Append(LastName).Append("\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(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as User).AreEqual; - } - - /// - /// Returns true if User instances are equal - /// - /// Instance of User to be compared - /// Boolean - public bool Equals(User 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) + this.Id.GetHashCode(); - if (this.Username != null) - { - hashCode = (hashCode * 59) + this.Username.GetHashCode(); - } - if (this.FirstName != null) - { - hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); - } - if (this.LastName != null) - { - hashCode = (hashCode * 59) + this.LastName.GetHashCode(); - } - if (this.Email != null) - { - hashCode = (hashCode * 59) + this.Email.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - if (this.Phone != null) - { - hashCode = (hashCode * 59) + this.Phone.GetHashCode(); - } - hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); - if (this.ObjectWithNoDeclaredProps != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); - } - if (this.ObjectWithNoDeclaredPropsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); - } - if (this.AnyTypeProp != null) - { - hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); - } - if (this.AnyTypePropNullable != null) - { - hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -258,4 +211,130 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type User + /// + public class UserJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override User Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "email": + email = reader.GetString(); + break; + case "firstName": + firstName = reader.GetString(); + break; + case "id": + id = reader.GetInt64(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "objectWithNoDeclaredProps": + objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref reader, options); + break; + case "password": + password = reader.GetString(); + break; + case "phone": + phone = reader.GetString(); + break; + case "userStatus": + userStatus = reader.GetInt32(); + break; + case "username": + username = reader.GetString(); + break; + case "anyTypeProp": + anyTypeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "anyTypePropNullable": + anyTypePropNullable = JsonSerializer.Deserialize(ref reader, options); + break; + case "objectWithNoDeclaredPropsNullable": + objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new User(email, firstName, id, lastName, objectWithNoDeclaredProps, password, phone, userStatus, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("email", user.Email); + writer.WriteString("firstName", user.FirstName); + writer.WriteNumber("id", (int)user.Id); + writer.WriteString("lastName", user.LastName); + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, options); + writer.WriteString("password", user.Password); + writer.WriteString("phone", user.Phone); + writer.WriteNumber("userStatus", (int)user.UserStatus); + writer.WriteString("username", user.Username); + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, options); + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, options); + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs index 57c3ddbd8df..598bedad22c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,19 +26,32 @@ namespace Org.OpenAPITools.Model /// /// Whale /// - public partial class Whale : IEquatable, IValidatableObject + public partial class Whale : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// hasBaleen /// hasTeeth - public Whale(string className, bool hasBaleen = default, bool hasTeeth = default) + [JsonConstructor] + public Whale(string className, bool hasBaleen, bool hasTeeth) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (hasBaleen == null) + throw new ArgumentNullException("hasBaleen is a required property for Whale and cannot be null."); + + if (hasTeeth == null) + throw new ArgumentNullException("hasTeeth is a required property for Whale and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Whale and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; HasBaleen = hasBaleen; HasTeeth = hasTeeth; @@ -67,7 +79,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -84,50 +96,6 @@ namespace Org.OpenAPITools.Model 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 Whale).AreEqual; - } - - /// - /// Returns true if Whale instances are equal - /// - /// Instance of Whale to be compared - /// Boolean - public bool Equals(Whale 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); - hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Whale + /// + public class WhaleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Whale Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + bool hasBaleen = default; + bool hasTeeth = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "hasBaleen": + hasBaleen = reader.GetBoolean(); + break; + case "hasTeeth": + hasTeeth = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Whale(className, hasBaleen, hasTeeth); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", whale.ClassName); + writer.WriteBoolean("hasBaleen", whale.HasBaleen); + writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs index 452c2fe8b71..df74e95ec6e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Zebra /// - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// type - public Zebra(string className, TypeEnum type = default) : base() + [JsonConstructor] + public Zebra(string className, TypeEnum type) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (type == null) + throw new ArgumentNullException("type is a required property for Zebra and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Zebra and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Type = type; } @@ -51,23 +60,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Plains for value: plains /// - [EnumMember(Value = "plains")] Plains = 1, /// /// Enum Mountain for value: mountain /// - [EnumMember(Value = "mountain")] Mountain = 2, /// /// Enum Grevys for value: grevys /// - [EnumMember(Value = "grevys")] Grevys = 3 } + /// + /// Returns a TypeEnum + /// + /// + /// + public static TypeEnum TypeEnumFromString(string value) + { + if (value == "plains") + return TypeEnum.Plains; + + if (value == "mountain") + return TypeEnum.Mountain; + + if (value == "grevys") + return TypeEnum.Grevys; + + throw new NotImplementedException($"Could not convert value to type TypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -84,7 +129,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -101,49 +146,6 @@ namespace Org.OpenAPITools.Model 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 Zebra).AreEqual; - } - - /// - /// Returns true if Zebra instances are equal - /// - /// Instance of Zebra to be compared - /// Boolean - public bool Equals(Zebra 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 = base.GetHashCode(); - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -155,4 +157,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Zebra + /// + public class ZebraJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Zebra Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + Zebra.TypeEnum type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "type": + string typeRawValue = reader.GetString(); + type = Zebra.TypeEnumFromString(typeRawValue); + break; + default: + break; + } + } + } + + return new Zebra(className, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", zebra.ClassName); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); + if (typeRawValue != null) + writer.WriteString("type", typeRawValue); + else + writer.WriteNull("type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5fce68767c4..c1f59011db4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,9 +21,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md new file mode 100644 index 00000000000..e792f496009 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md @@ -0,0 +1,260 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net7.0', + 'validatable=true', + 'nullableReferenceTypes=false', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + '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 Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); + } + + 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 Org.OpenAPITools.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 +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 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: + + +### 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 + + +### bearer_test + + +- **Type**: Bearer Authentication + + +### http_basic_test + + +- **Type**: HTTP basic authentication + + +### http_signature_test + + + + +### 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 + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## 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: false +- 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: Org.OpenAPITools +- 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-netcore/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES index cf0f5c871be..65d841c450c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES @@ -92,31 +92,38 @@ docs/scripts/git_push.ps1 docs/scripts/git_push.sh src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md src/Org.OpenAPITools/Api/AnotherFakeApi.cs src/Org.OpenAPITools/Api/DefaultApi.cs src/Org.OpenAPITools/Api/FakeApi.cs src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +src/Org.OpenAPITools/Api/IApi.cs src/Org.OpenAPITools/Api/PetApi.cs src/Org.OpenAPITools/Api/StoreApi.cs src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs src/Org.OpenAPITools/Client/ApiKeyToken.cs src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/HostConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningToken.cs -src/Org.OpenAPITools/Client/IApi.cs src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs src/Org.OpenAPITools/Client/OAuthToken.cs -src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs src/Org.OpenAPITools/Client/RateLimitProvider`1.cs src/Org.OpenAPITools/Client/TokenBase.cs src/Org.OpenAPITools/Client/TokenContainer`1.cs src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs src/Org.OpenAPITools/Model/Activity.cs src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -197,3 +204,4 @@ src/Org.OpenAPITools/Model/User.cs src/Org.OpenAPITools/Model/Whale.cs src/Org.OpenAPITools/Model/Zebra.cs src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/README.md index a8ac54da0c4..f9c1c7f7462 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/README.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/README.md @@ -1,259 +1 @@ # Created with Openapi Generator - - -## Run the following powershell command to generate the library - -```ps1 -$properties = @( - 'apiName=Api', - 'targetFramework=netstandard2.0', - 'validatable=true', - 'nullableReferenceTypes=', - 'hideGenerationTimestamp=true', - 'packageVersion=1.0.0', - 'packageAuthors=OpenAPI', - 'packageCompany=OpenAPI', - 'packageCopyright=No Copyright', - 'packageDescription=A library generated from a OpenAPI doc', - 'packageName=Org.OpenAPITools', - '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 Org.OpenAPITools.Api; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Model; - -namespace YourProject -{ - public class Program - { - public static async Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); - var api = host.Services.GetRequiredService(); - ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); - } - - 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. - - -## 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 -- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later -- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.1 or later -- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.7.0 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: - - -### 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 - - -### bearer_test - - -- **Type**: Bearer Authentication - - -### http_basic_test - - -- **Type**: HTTP basic authentication - - -### http_signature_test - - - - -### 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 - -## Build -- SDK version: 1.0.0 -- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen - -## 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: -- 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: Org.OpenAPITools -- packageTags: -- packageTitle: OpenAPI Library -- packageVersion: 1.0.0 -- releaseNote: Minor update -- returnICollection: false -- sortParamsByRequiredFlag: -- sourceFolder: src -- targetFramework: netstandard2.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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md index f17e38282a0..b815f20b5a0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md @@ -631,7 +631,7 @@ No authorization required # **TestBodyWithQueryParams** -> void TestBodyWithQueryParams (string query, User user) +> void TestBodyWithQueryParams (User user, string query) @@ -652,12 +652,12 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new FakeApi(config); - var query = "query_example"; // string | var user = new User(); // User | + var query = "query_example"; // string | try { - apiInstance.TestBodyWithQueryParams(query, user); + apiInstance.TestBodyWithQueryParams(user, query); } catch (ApiException e) { @@ -676,7 +676,7 @@ This returns an ApiResponse object which contains the response data, status code ```csharp try { - apiInstance.TestBodyWithQueryParamsWithHttpInfo(query, user); + apiInstance.TestBodyWithQueryParamsWithHttpInfo(user, query); } catch (ApiException e) { @@ -690,8 +690,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **query** | **string** | | | | **user** | [**User**](User.md) | | | +| **query** | **string** | | | ### Return type @@ -807,7 +807,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null) +> void TestEndpointParameters (byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -834,17 +834,17 @@ namespace Example config.Password = "YOUR_PASSWORD"; var apiInstance = new FakeApi(config); + var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | None var number = 8.14D; // decimal | None var _double = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | 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 _float = 3.4F; // float? | None (optional) var integer = 56; // int? | None (optional) var int32 = 56; // int? | None (optional) var int64 = 789L; // long? | None (optional) - var _float = 3.4F; // float? | None (optional) var _string = "_string_example"; // string | None (optional) - var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) - var date = DateTime.Parse("2013-10-20"); // DateTime? | 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") @@ -852,7 +852,7 @@ namespace Example try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -872,7 +872,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + apiInstance.TestEndpointParametersWithHttpInfo(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } catch (ApiException e) { @@ -886,17 +886,17 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| +| **_byte** | **byte[]** | None | | | **number** | **decimal** | None | | | **_double** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **_byte** | **byte[]** | None | | +| **date** | **DateTime?** | None | [optional] | +| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | +| **_float** | **float?** | None | [optional] | | **integer** | **int?** | None | [optional] | | **int32** | **int?** | None | [optional] | | **int64** | **long?** | None | [optional] | -| **_float** | **float?** | None | [optional] | | **_string** | **string** | None | [optional] | -| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | -| **date** | **DateTime?** | None | [optional] | | **password** | **string** | None | [optional] | | **callback** | **string** | None | [optional] | | **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | @@ -925,7 +925,7 @@ void (empty response body) # **TestEnumParameters** -> void TestEnumParameters (List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null) +> 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 @@ -950,17 +950,17 @@ namespace Example 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 enumQueryInteger = 1; // int? | Query parameter enum test (double) (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 enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) (default to $) var enumFormString = "_abc"; // string | Form parameter enum test (string) (optional) (default to -efg) try { // To test enum parameters - apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -980,7 +980,7 @@ This returns an ApiResponse object which contains the response data, status code try { // To test enum parameters - apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } catch (ApiException e) { @@ -996,11 +996,11 @@ catch (ApiException e) |------|------|-------------|-------| | **enumHeaderStringArray** | [**List<string>**](string.md) | Header parameter enum test (string array) | [optional] | | **enumQueryStringArray** | [**List<string>**](string.md) | Query parameter enum test (string array) | [optional] | -| **enumQueryInteger** | **int?** | Query parameter enum test (double) | [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] | -| **enumFormStringArray** | [**List<string>**](string.md) | Form parameter enum test (string array) | [optional] [default to $] | | **enumFormString** | **string** | Form parameter enum test (string) | [optional] [default to -efg] | ### Return type @@ -1027,7 +1027,7 @@ No authorization required # **TestGroupParameters** -> void TestGroupParameters (int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null) +> void TestGroupParameters (bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null) Fake endpoint to test group parameters (optional) @@ -1053,17 +1053,17 @@ namespace Example config.AccessToken = "YOUR_BEARER_TOKEN"; var apiInstance = new FakeApi(config); - var requiredStringGroup = 56; // int | Required String in group parameters 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 stringGroup = 56; // int? | String in group parameters (optional) 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(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1083,7 +1083,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Fake endpoint to test group parameters (optional) - apiInstance.TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + apiInstance.TestGroupParametersWithHttpInfo(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } catch (ApiException e) { @@ -1097,11 +1097,11 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | +| **requiredStringGroup** | **int** | Required String in group parameters | | | **requiredInt64Group** | **long** | Required Integer in group parameters | | -| **stringGroup** | **int?** | String in group parameters | [optional] | | **booleanGroup** | **bool?** | Boolean in group parameters | [optional] | +| **stringGroup** | **int?** | String in group parameters | [optional] | | **int64Group** | **long?** | Integer in group parameters | [optional] | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md index 8ece47af9ca..da6486e4cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md @@ -664,7 +664,7 @@ void (empty response body) # **UploadFile** -> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) +> ApiResponse UploadFile (long petId, System.IO.Stream file = null, string additionalMetadata = null) uploads an image @@ -689,13 +689,13 @@ namespace Example var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to update - var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) 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, additionalMetadata, file); + ApiResponse result = apiInstance.UploadFile(petId, file, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -716,7 +716,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image - ApiResponse response = apiInstance.UploadFileWithHttpInfo(petId, additionalMetadata, file); + 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); @@ -734,8 +734,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| | **petId** | **long** | ID of pet to update | | -| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | | **file** | **System.IO.Stream****System.IO.Stream** | file to upload | [optional] | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | ### Return type @@ -760,7 +760,7 @@ catch (ApiException e) # **UploadFileWithRequiredFile** -> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) +> ApiResponse UploadFileWithRequiredFile (System.IO.Stream requiredFile, long petId, string additionalMetadata = null) uploads an image (required) @@ -784,14 +784,14 @@ namespace Example config.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(config); - var petId = 789L; // long | ID of pet to update 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(petId, requiredFile, additionalMetadata); + ApiResponse result = apiInstance.UploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); Debug.WriteLine(result); } catch (ApiException e) @@ -812,7 +812,7 @@ This returns an ApiResponse object which contains the response data, status code try { // uploads an image (required) - ApiResponse response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + 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); @@ -829,8 +829,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **petId** | **long** | ID of pet to update | | | **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 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md index fd1c1a7d62b..a862c8c112a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md @@ -623,7 +623,7 @@ No authorization required # **UpdateUser** -> void UpdateUser (string username, User user) +> void UpdateUser (User user, string username) Updated user @@ -646,13 +646,13 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; var apiInstance = new UserApi(config); - var username = "username_example"; // string | name that need to be deleted var user = new User(); // User | Updated user object + var username = "username_example"; // string | name that need to be deleted try { // Updated user - apiInstance.UpdateUser(username, user); + apiInstance.UpdateUser(user, username); } catch (ApiException e) { @@ -672,7 +672,7 @@ This returns an ApiResponse object which contains the response data, status code try { // Updated user - apiInstance.UpdateUserWithHttpInfo(username, user); + apiInstance.UpdateUserWithHttpInfo(user, username); } catch (ApiException e) { @@ -686,8 +686,8 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| -| **username** | **string** | name that need to be deleted | | | **user** | [**User**](User.md) | Updated user object | | +| **username** | **string** | name that need to be deleted | | ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md index 1f919450009..f79869f95a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md @@ -4,14 +4,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapProperty** | **Dictionary<string, string>** | | [optional] +**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] -**Anytype1** | **Object** | | [optional] +**MapProperty** | **Dictionary<string, string>** | | [optional] **MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] -**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ApiResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ApiResponse.md index bc808ceeae3..d89ed1a25dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ApiResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ApiResponse.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | **int** | | [optional] -**Type** | **string** | | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ArrayTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ArrayTest.md index 32365e6d4d0..ed572120cd6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ArrayTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ArrayTest.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayOfString** | **List<string>** | | [optional] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Capitalization.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Capitalization.md index fde98a967ef..9e225c17232 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Capitalization.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Capitalization.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SmallCamel** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [optional] **CapitalCamel** | **string** | | [optional] -**SmallSnake** | **string** | | [optional] **CapitalSnake** | **string** | | [optional] **SCAETHFlowPoints** | **string** | | [optional] -**ATT_NAME** | **string** | Name of the pet | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Category.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Category.md index c2cf3f8e919..6eb0a2e13ea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Category.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Category.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Name** | **string** | | [default to "default-name"] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ClassModel.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ClassModel.md index bb35816c914..a098828a04f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ClassModel.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ClassModel.md @@ -5,7 +5,7 @@ Model for testing model with \"_class\" property Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Class** | **string** | | [optional] +**ClassProperty** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md index 18117e6c938..fcee9662afb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md @@ -6,8 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] -**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **Shapes** | [**List<Shape>**](Shape.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md index 2a27962cc52..7467f67978c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**JustSymbol** | **string** | | [optional] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md index 71602270bab..53bbfe31e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**EnumStringRequired** | **string** | | -**EnumString** | **string** | | [optional] **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] -**OuterEnumInteger** | **OuterEnumInteger** | | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FooGetDefaultResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FooGetDefaultResponse.md index 47e50daca3e..78c99facf59 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FooGetDefaultResponse.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FooGetDefaultResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] +**StringProperty** | [**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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md index 0b92c2fb10a..4e34a6d18b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md @@ -4,22 +4,22 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Number** | **decimal** | | -**Byte** | **byte[]** | | +**Binary** | **System.IO.Stream** | | [optional] +**ByteProperty** | **byte[]** | | **Date** | **DateTime** | | -**Password** | **string** | | -**Integer** | **int** | | [optional] +**DateTime** | **DateTime** | | [optional] +**DecimalProperty** | **decimal** | | [optional] +**DoubleProperty** | **double** | | [optional] +**FloatProperty** | **float** | | [optional] **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] -**Float** | **float** | | [optional] -**Double** | **double** | | [optional] -**Decimal** | **decimal** | | [optional] -**String** | **string** | | [optional] -**Binary** | **System.IO.Stream** | | [optional] -**DateTime** | **DateTime** | | [optional] -**Uuid** | **Guid** | | [optional] +**Integer** | **int** | | [optional] +**Number** | **decimal** | | +**Password** | **string** | | **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] +**StringProperty** | **string** | | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md index aaee09f7870..5dd27228bb0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md index 031d2b96065..0bac85a8e83 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **Guid** | | [optional] **DateTime** | **DateTime** | | [optional] **Map** | [**Dictionary<string, Animal>**](Animal.md) | | [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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Model200Response.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Model200Response.md index 8bc8049f46f..93139e1d1aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Model200Response.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Model200Response.md @@ -5,8 +5,8 @@ Model for testing model name starting with number Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**ClassProperty** | **string** | | [optional] **Name** | **int** | | [optional] -**Class** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ModelClient.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ModelClient.md index 9e0e83645f3..51cf0636e72 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ModelClient.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ModelClient.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_Client** | **string** | | [optional] +**_ClientProperty** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Name.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Name.md index 2ee782c0c54..11f49b9fd40 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Name.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Name.md @@ -6,8 +6,8 @@ Model for testing model name same as property name Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **NameProperty** | **int** | | -**SnakeCase** | **int** | | [optional] [readonly] **Property** | **string** | | [optional] +**SnakeCase** | **int** | | [optional] [readonly] **_123Number** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md index d4a19d1856b..ac86336ea70 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**IntegerProp** | **int?** | | [optional] -**NumberProp** | **decimal?** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool?** | | [optional] -**StringProp** | **string** | | [optional] **DateProp** | **DateTime?** | | [optional] **DatetimeProp** | **DateTime?** | | [optional] -**ArrayNullableProp** | **List<Object>** | | [optional] -**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**IntegerProp** | **int?** | | [optional] +**NumberProp** | **decimal?** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] -**ObjectItemsNullable** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ObjectWithDeprecatedFields.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ObjectWithDeprecatedFields.md index b737f7d757a..9f44c24d19a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ObjectWithDeprecatedFields.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/ObjectWithDeprecatedFields.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Uuid** | **string** | | [optional] -**Id** | **decimal** | | [optional] -**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/OuterComposite.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/OuterComposite.md index abf676810fb..8985c59d094 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/OuterComposite.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/OuterComposite.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**MyBoolean** | **bool** | | [optional] **MyNumber** | **decimal** | | [optional] **MyString** | **string** | | [optional] -**MyBoolean** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md index 7de10304abf..b13bb576b45 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | -**Id** | **long** | | [optional] -**Category** | [**Category**](Category.md) | | [optional] -**Tags** | [**List<Tag>**](Tag.md) | | [optional] **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/SpecialModelName.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/SpecialModelName.md index 662fa6f4a38..b48f3490005 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/SpecialModelName.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/SpecialModelName.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**SpecialPropertyName** | **long** | | [optional] **SpecialModelNameProperty** | **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-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md index a0f0d223899..455f031674d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Username** | **string** | | [optional] -**FirstName** | **string** | | [optional] -**LastName** | **string** | | [optional] **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] -**ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs index fea7e39428f..30f54c0aab5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class AnotherFakeApiTests : ApiTestsBase { - private readonly IAnotherFakeApi _instance; + private readonly IApi.IAnotherFakeApi _instance; public AnotherFakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index 88d6fc1f488..75e37de2412 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Extensions.Hosting; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; /* ********************************************************************************* @@ -49,7 +50,7 @@ namespace Org.OpenAPITools.Test.Api } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureApi((context, options) => + .ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration[""], timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 16f60704f2a..d79076dcd63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class DefaultApiTests : ApiTestsBase { - private readonly IDefaultApi _instance; + private readonly IApi.IDefaultApi _instance; public DefaultApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 4eee3d2b6eb..256df5697c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -13,7 +13,8 @@ using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Security.Cryptography; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; using Xunit; namespace Org.OpenAPITools.Test.Api @@ -24,7 +25,7 @@ namespace Org.OpenAPITools.Test.Api public class DependencyInjectionTest { private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -45,7 +46,7 @@ namespace Org.OpenAPITools.Test.Api .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, options) => + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); @@ -121,25 +122,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -149,25 +150,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void ConfigureApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -177,25 +178,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithAClientTest() { - var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -205,25 +206,25 @@ namespace Org.OpenAPITools.Test.Api [Fact] public void AddApiWithoutAClientTest() { - var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index b70f2a8adc7..4c965120e69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeApiTests : ApiTestsBase { - private readonly IFakeApi _instance; + private readonly IApi.IFakeApi _instance; public FakeApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -131,9 +131,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestBodyWithQueryParamsAsyncTest() { - string query = default; User user = default; - await _instance.TestBodyWithQueryParamsAsync(query, user); + string query = default; + await _instance.TestBodyWithQueryParamsAsync(user, query); } /// @@ -153,21 +153,21 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestEndpointParametersAsyncTest() { + byte[] _byte = default; decimal number = default; double _double = default; string patternWithoutDelimiter = default; - byte[] _byte = default; + DateTime? date = default; + System.IO.Stream binary = default; + float? _float = default; int? integer = default; int? int32 = default; long? int64 = default; - float? _float = default; string _string = default; - System.IO.Stream binary = default; - DateTime? date = default; string password = default; string callback = default; DateTime? dateTime = default; - await _instance.TestEndpointParametersAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime); + await _instance.TestEndpointParametersAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); } /// @@ -178,13 +178,13 @@ namespace Org.OpenAPITools.Test.Api { List enumHeaderStringArray = default; List enumQueryStringArray = default; - int? enumQueryInteger = default; double? enumQueryDouble = default; + int? enumQueryInteger = default; + List enumFormStringArray = default; string enumHeaderString = default; string enumQueryString = default; - List enumFormStringArray = default; string enumFormString = default; - await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString); + await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); } /// @@ -193,13 +193,13 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task TestGroupParametersAsyncTest() { - int requiredStringGroup = default; bool requiredBooleanGroup = default; + int requiredStringGroup = default; long requiredInt64Group = default; - int? stringGroup = default; bool? booleanGroup = default; + int? stringGroup = default; long? int64Group = default; - await _instance.TestGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + await _instance.TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs index 0e8d44fe985..5a34bf585f0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class FakeClassnameTags123ApiTests : ApiTestsBase { - private readonly IFakeClassnameTags123Api _instance; + private readonly IApi.IFakeClassnameTags123Api _instance; public FakeClassnameTags123ApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index 92922eda1b7..8ebf3b80bf4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class PetApiTests : ApiTestsBase { - private readonly IPetApi _instance; + private readonly IApi.IPetApi _instance; public PetApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -134,9 +134,9 @@ namespace Org.OpenAPITools.Test.Api public async Task UploadFileAsyncTest() { long petId = default; - string additionalMetadata = default; System.IO.Stream file = default; - var response = await _instance.UploadFileAsync(petId, additionalMetadata, file); + string additionalMetadata = default; + var response = await _instance.UploadFileAsync(petId, file, additionalMetadata); Assert.IsType(response); } @@ -146,10 +146,10 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UploadFileWithRequiredFileAsyncTest() { - long petId = default; System.IO.Stream requiredFile = default; + long petId = default; string additionalMetadata = default; - var response = await _instance.UploadFileWithRequiredFileAsync(petId, requiredFile, additionalMetadata); + var response = await _instance.UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata); Assert.IsType(response); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index 98748893e32..679d6488380 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class StoreApiTests : ApiTestsBase { - private readonly IStoreApi _instance; + private readonly IApi.IStoreApi _instance; public StoreApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index 0df256733af..b8006066faf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; +using Org.OpenAPITools.IApi; using Org.OpenAPITools.Model; @@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api /// public sealed class UserApiTests : ApiTestsBase { - private readonly IUserApi _instance; + private readonly IApi.IUserApi _instance; public UserApiTests(): base(Array.Empty()) { - _instance = _host.Services.GetRequiredService(); + _instance = _host.Services.GetRequiredService(); } @@ -129,9 +129,9 @@ namespace Org.OpenAPITools.Test.Api [Fact (Skip = "not implemented")] public async Task UpdateUserAsyncTest() { - string username = default; User user = default; - await _instance.UpdateUserAsync(username, user); + string username = default; + await _instance.UpdateUserAsync(user, username); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs index f211a64884a..174a7e333af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityOutputElementRepresentationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs index afe9e846ee9..c7479a3c343 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ActivityTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index 9ab029ed097..95bd1593503 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'MapProperty' + /// Test the property 'EmptyMap' /// [Fact] - public void MapPropertyTest() + public void EmptyMapTest() { - // TODO unit test for the property 'MapProperty' + // TODO unit test for the property 'EmptyMap' } /// /// Test the property 'MapOfMapProperty' @@ -73,12 +72,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapOfMapProperty' } /// - /// Test the property 'Anytype1' + /// Test the property 'MapProperty' /// [Fact] - public void Anytype1Test() + public void MapPropertyTest() { - // TODO unit test for the property 'Anytype1' + // TODO unit test for the property 'MapProperty' } /// /// Test the property 'MapWithUndeclaredPropertiesAnytype1' @@ -105,14 +104,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' } /// - /// Test the property 'EmptyMap' - /// - [Fact] - public void EmptyMapTest() - { - // TODO unit test for the property 'EmptyMap' - } - /// /// Test the property 'MapWithUndeclaredPropertiesString' /// [Fact] @@ -120,6 +111,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index ced34a4faad..8c38ac47af7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 2a2e098e608..a2a9a2d49de 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Code' } /// - /// Test the property 'Type' - /// - [Fact] - public void TypeTest() - { - // TODO unit test for the property 'Type' - } - /// /// Test the property 'Message' /// [Fact] @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs index f945f659368..0610780d65d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs index 468d60184ad..e0bd59e7732 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs index 0b259d7d391..8f046a0bf6b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs index 27f312ad25f..53b2fe30fdb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs index a433e8c87cf..df87ba3aaaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'ArrayOfString' - /// - [Fact] - public void ArrayOfStringTest() - { - // TODO unit test for the property 'ArrayOfString' - } /// /// Test the property 'ArrayArrayOfInteger' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs index 8a6eeb82eee..6f31ba2029b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs index 8d8cc376b03..6cb6c62ffd0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs index 3cdccaa7595..9798a17577b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs index 185c83666fc..b84c7c85a7d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'SmallCamel' + /// Test the property 'ATT_NAME' /// [Fact] - public void SmallCamelTest() + public void ATT_NAMETest() { - // TODO unit test for the property 'SmallCamel' + // TODO unit test for the property 'ATT_NAME' } /// /// Test the property 'CapitalCamel' @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'CapitalCamel' } /// - /// Test the property 'SmallSnake' - /// - [Fact] - public void SmallSnakeTest() - { - // TODO unit test for the property 'SmallSnake' - } - /// /// Test the property 'CapitalSnake' /// [Fact] @@ -97,12 +88,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'SCAETHFlowPoints' } /// - /// Test the property 'ATT_NAME' + /// Test the property 'SmallCamel' /// [Fact] - public void ATT_NAMETest() + public void SmallCamelTest() { - // TODO unit test for the property 'ATT_NAME' + // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs index fb51c28489c..3498bb0c152 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatTests.cs index 9c3c48ffefe..402a476d079 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index 621877aa973..822f8241fa0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } /// /// Test the property 'Id' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs index 49a53932490..d4de4c47417 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs index 0fe3ebfa06e..f1b0aa1005c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs index d29472e83aa..2e6c120d8fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Class' + /// Test the property 'ClassProperty' /// [Fact] - public void ClassTest() + public void ClassPropertyTest() { - // TODO unit test for the property 'Class' + // TODO unit test for the property 'ClassProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs index 6c50fe7aab5..3f2f96e73a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs index 572d9bffa79..087d38674bb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs index 1da5f4011c9..85ecbfdda55 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs index b22a4442096..1e86d761507 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogTests.cs index bf906f01bc6..ef2eabfca31 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0709ad9eeb3..c38867cb5ae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -73,14 +72,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ShapeOrNull' } /// - /// Test the property 'NullableShape' - /// - [Fact] - public void NullableShapeTest() - { - // TODO unit test for the property 'NullableShape' - } - /// /// Test the property 'Shapes' /// [Fact] @@ -88,6 +79,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Shapes' } + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs index 5779ca29477..ee3d000f32f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'JustSymbol' - /// - [Fact] - public void JustSymbolTest() - { - // TODO unit test for the property 'JustSymbol' - } /// /// Test the property 'ArrayEnum' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs index a17738c5cbc..e2fc2d02282 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index a22c39ca845..60e3aca92bd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'EnumStringRequired' - /// - [Fact] - public void EnumStringRequiredTest() - { - // TODO unit test for the property 'EnumStringRequired' - } - /// - /// Test the property 'EnumString' - /// - [Fact] - public void EnumStringTest() - { - // TODO unit test for the property 'EnumString' - } /// /// Test the property 'EnumInteger' /// @@ -97,20 +80,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumNumber' } /// - /// Test the property 'OuterEnum' + /// Test the property 'EnumString' /// [Fact] - public void OuterEnumTest() + public void EnumStringTest() { - // TODO unit test for the property 'OuterEnum' + // TODO unit test for the property 'EnumString' } /// - /// Test the property 'OuterEnumInteger' + /// Test the property 'EnumStringRequired' /// [Fact] - public void OuterEnumIntegerTest() + public void EnumStringRequiredTest() { - // TODO unit test for the property 'OuterEnumInteger' + // TODO unit test for the property 'EnumStringRequired' } /// /// Test the property 'OuterEnumDefaultValue' @@ -121,6 +104,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -128,6 +119,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs index 9ca755c4b07..9ab78a59779 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs index 9f45b4fe89d..9836a779bf0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileTests.cs index 761bb72a844..4f0e7079bc8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs index 0154d528418..b7313941a69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'String' + /// Test the property 'StringProperty' /// [Fact] - public void StringTest() + public void StringPropertyTest() { - // TODO unit test for the property 'String' + // TODO unit test for the property 'StringProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooTests.cs index 0b6ed52edbd..c0bdf85f9b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index 707847bbcd1..d3a978bdc4c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,20 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Number' + /// Test the property 'Binary' /// [Fact] - public void NumberTest() + public void BinaryTest() { - // TODO unit test for the property 'Number' + // TODO unit test for the property 'Binary' } /// - /// Test the property 'Byte' + /// Test the property 'ByteProperty' /// [Fact] - public void ByteTest() + public void BytePropertyTest() { - // TODO unit test for the property 'Byte' + // TODO unit test for the property 'ByteProperty' } /// /// Test the property 'Date' @@ -81,20 +80,36 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Date' } /// - /// Test the property 'Password' + /// Test the property 'DateTime' /// [Fact] - public void PasswordTest() + public void DateTimeTest() { - // TODO unit test for the property 'Password' + // TODO unit test for the property 'DateTime' } /// - /// Test the property 'Integer' + /// Test the property 'DecimalProperty' /// [Fact] - public void IntegerTest() + public void DecimalPropertyTest() { - // TODO unit test for the property 'Integer' + // TODO unit test for the property 'DecimalProperty' + } + /// + /// Test the property 'DoubleProperty' + /// + [Fact] + public void DoublePropertyTest() + { + // TODO unit test for the property 'DoubleProperty' + } + /// + /// Test the property 'FloatProperty' + /// + [Fact] + public void FloatPropertyTest() + { + // TODO unit test for the property 'FloatProperty' } /// /// Test the property 'Int32' @@ -113,60 +128,28 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Int64' } /// - /// Test the property 'Float' + /// Test the property 'Integer' /// [Fact] - public void FloatTest() + public void IntegerTest() { - // TODO unit test for the property 'Float' + // TODO unit test for the property 'Integer' } /// - /// Test the property 'Double' + /// Test the property 'Number' /// [Fact] - public void DoubleTest() + public void NumberTest() { - // TODO unit test for the property 'Double' + // TODO unit test for the property 'Number' } /// - /// Test the property 'Decimal' + /// Test the property 'Password' /// [Fact] - public void DecimalTest() + public void PasswordTest() { - // TODO unit test for the property 'Decimal' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' + // TODO unit test for the property 'Password' } /// /// Test the property 'PatternWithDigits' @@ -184,6 +167,22 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'PatternWithDigitsAndDelimiter' } + /// + /// Test the property 'StringProperty' + /// + [Fact] + public void StringPropertyTest() + { + // TODO unit test for the property 'StringProperty' + } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs index 3a0b55b93e3..3ef884e59c6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs index ddc424d56ea..9ab6b7f2781 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs index cbd35f9173c..036c5641cf4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index faa4930944b..182cf7350b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs index 651a9f0ce30..d9a07efcf9a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs index 857190a3334..d29edf5dd10 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs index 8e0dae93420..2fed6f0b4cc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ListTests.cs index 2ed828d0520..398a4644921 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ListTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs index 6477ab950fa..0889d80a708 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs index 20036e1c905..0dc95aa6b23 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,22 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// 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' - } /// /// Test the property 'DirectMap' /// @@ -88,6 +71,22 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index f56cd715f45..d94f882e0a2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'Uuid' - /// - [Fact] - public void UuidTest() - { - // TODO unit test for the property 'Uuid' - } /// /// Test the property 'DateTime' /// @@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Map' } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs index e25478618f2..31f2a754314 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'ClassProperty' + /// + [Fact] + public void ClassPropertyTest() + { + // TODO unit test for the property 'ClassProperty' + } /// /// Test the property 'Name' /// @@ -64,14 +71,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Name' } - /// - /// Test the property 'Class' - /// - [Fact] - public void ClassTest() - { - // TODO unit test for the property 'Class' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 24a9e263158..40b3700ce95 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '_Client' + /// Test the property '_ClientProperty' /// [Fact] - public void _ClientTest() + public void _ClientPropertyTest() { - // TODO unit test for the property '_Client' + // TODO unit test for the property '_ClientProperty' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NameTests.cs index 61f8ad11379..523b3e050aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'NameProperty' } /// - /// Test the property 'SnakeCase' - /// - [Fact] - public void SnakeCaseTest() - { - // TODO unit test for the property 'SnakeCase' - } - /// /// Test the property 'Property' /// [Fact] @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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 '_123Number' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 8f00505612a..adf7c14f131 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,36 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'IntegerProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void IntegerPropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'IntegerProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// - /// Test the property 'NumberProp' + /// Test the property 'ObjectItemsNullable' /// [Fact] - public void NumberPropTest() + public void ObjectItemsNullableTest() { - // TODO unit test for the property 'NumberProp' + // 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' @@ -81,14 +96,6 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'BooleanProp' } /// - /// Test the property 'StringProp' - /// - [Fact] - public void StringPropTest() - { - // TODO unit test for the property 'StringProp' - } - /// /// Test the property 'DateProp' /// [Fact] @@ -105,36 +112,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DatetimeProp' } /// - /// Test the property 'ArrayNullableProp' + /// Test the property 'IntegerProp' /// [Fact] - public void ArrayNullablePropTest() + public void IntegerPropTest() { - // TODO unit test for the property 'ArrayNullableProp' + // TODO unit test for the property 'IntegerProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'NumberProp' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void NumberPropTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' - } - /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - /// - /// Test the property 'ObjectNullableProp' - /// - [Fact] - public void ObjectNullablePropTest() - { - // TODO unit test for the property 'ObjectNullableProp' + // TODO unit test for the property 'NumberProp' } /// /// Test the property 'ObjectAndItemsNullableProp' @@ -145,12 +136,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'ObjectAndItemsNullableProp' } /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ObjectNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ObjectNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs index 8202ef63914..734d03e5e7a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs index 3a06cb020b2..5db923c1d3f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs index 82f93fab48c..9e9b651f818 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Uuid' + /// Test the property 'Bars' /// [Fact] - public void UuidTest() + public void BarsTest() { - // TODO unit test for the property 'Uuid' - } - /// - /// Test the property 'Id' - /// - [Fact] - public void IdTest() - { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'Bars' } /// /// Test the property 'DeprecatedRef' @@ -81,12 +72,20 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'DeprecatedRef' } /// - /// Test the property 'Bars' + /// Test the property 'Id' /// [Fact] - public void BarsTest() + public void IdTest() { - // TODO unit test for the property 'Bars' + // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs index cf5c561c547..10682e72f21 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs index 2efda0db59c..8c176d9f94c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,14 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } /// /// Test the property 'MyNumber' /// @@ -72,14 +79,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'MyString' } - /// - /// Test the property 'MyBoolean' - /// - [Fact] - public void MyBooleanTest() - { - // TODO unit test for the property 'MyBoolean' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs index 986fff774c4..9f6d8b52b6c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs index 015d5dab945..e51365edb27 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs index 385e899110a..36e6a060f97 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs index f47304767b9..b38c693d1a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs index 1e17568ed33..34cae43eac1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs index 28ea4d8478d..66cfbf7bdb5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,6 +55,22 @@ namespace Org.OpenAPITools.Test.Model } + /// + /// 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' /// @@ -73,20 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Id' + /// Test the property 'Status' /// [Fact] - public void IdTest() + public void StatusTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Category' - /// - [Fact] - public void CategoryTest() - { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Status' } /// /// Test the property 'Tags' @@ -96,14 +103,6 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'Tags' } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PigTests.cs index a66befe8f58..0e85eabf160 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs index eff3c6ddc9b..98aad34f4b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs index 6eef9f4c816..42243bd29c0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs index 3d62673d093..e15b2c5c749 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs index dc3d0fad54c..7e99972f26e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs index 65fa199fe35..9969564490d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs index 018dffb5964..cad95d2963c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs index 7bd0bc86f96..3129f3775c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs index ef564357648..a33da20eda6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs index 783a9657ed4..b2d995af504 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs index 3bcd65e792d..0221971c076 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 91682a7afd6..1a5bb10af80 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -56,14 +55,6 @@ namespace Org.OpenAPITools.Test.Model } - /// - /// Test the property 'SpecialPropertyName' - /// - [Fact] - public void SpecialPropertyNameTest() - { - // TODO unit test for the property 'SpecialPropertyName' - } /// /// Test the property 'SpecialModelNameProperty' /// @@ -72,6 +63,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialModelNameProperty' } + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TagTests.cs index 6d56232d0a7..92a5f823659 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs index fba65470bee..924d6b42d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs index bdaab0b4796..9701da6a541 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs index a7b095e4c28..a464c80c84c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { @@ -57,20 +56,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property 'Id' + /// Test the property 'Email' /// [Fact] - public void IdTest() + public void EmailTest() { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Username' - /// - [Fact] - public void UsernameTest() - { - // TODO unit test for the property 'Username' + // TODO unit test for the property 'Email' } /// /// Test the property 'FirstName' @@ -81,6 +72,14 @@ namespace Org.OpenAPITools.Test.Model // 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] @@ -89,12 +88,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'LastName' } /// - /// Test the property 'Email' + /// Test the property 'ObjectWithNoDeclaredProps' /// [Fact] - public void EmailTest() + public void ObjectWithNoDeclaredPropsTest() { - // TODO unit test for the property 'Email' + // TODO unit test for the property 'ObjectWithNoDeclaredProps' } /// /// Test the property 'Password' @@ -121,20 +120,12 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'UserStatus' } /// - /// Test the property 'ObjectWithNoDeclaredProps' + /// Test the property 'Username' /// [Fact] - public void ObjectWithNoDeclaredPropsTest() + public void UsernameTest() { - // TODO unit test for the property 'ObjectWithNoDeclaredProps' - } - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + // TODO unit test for the property 'Username' } /// /// Test the property 'AnyTypeProp' @@ -152,6 +143,14 @@ namespace Org.OpenAPITools.Test.Model { // 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs index 9b82c29c8fd..91a7b21f213 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs index 39e0561fe0f..08b1c6056c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -18,7 +18,6 @@ using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; -using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index a68e9179c81..06b106b96d3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -16,5 +16,4 @@ - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index b2b9905d3a7..4c37cee2cda 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IAnotherFakeApi : IApi { @@ -48,21 +49,19 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); } + Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class AnotherFakeApi : IAnotherFakeApi + public partial class AnotherFakeApi : IApi.IAnotherFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -119,6 +118,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -159,6 +167,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnCall123TestSpecialTags(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCall123TestSpecialTags(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCall123TestSpecialTags(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test special tags To test special tags and operation ID starting with number /// @@ -168,18 +216,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnCall123TestSpecialTags(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -189,6 +233,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -198,7 +244,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -208,31 +254,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("PATCH"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCall123TestSpecialTags(apiResponse, modelClient); + } return apiResponse; } @@ -240,8 +279,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCall123TestSpecialTags(e, "/another-fake/dummy", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/DefaultApi.cs index 2f874775c60..fccc25399cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IDefaultApi : IApi { @@ -46,21 +47,19 @@ namespace Org.OpenAPITools.Api /// Thrown when fails to make API call /// Cancellation Token to cancel the request. /// Task of ApiResponse<FooGetDefaultResponse> - Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); } + Task FooGetAsync(System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class DefaultApi : IDefaultApi + public partial class DefaultApi : IApi.IDefaultApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -117,6 +116,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// /// @@ -155,6 +163,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFooGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFooGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFooGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// @@ -163,16 +199,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FooGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFooGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/foo"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -183,31 +224,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFooGet(apiResponse); + } return apiResponse; } @@ -215,8 +249,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFooGet(e, "/foo", uriBuilder.Path); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs index f9f02ecc219..c017ba3eccb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeApi : IApi { @@ -47,6 +48,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<HealthCheckResult> Task FakeHealthGetAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -70,6 +72,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<bool> Task FakeOuterBooleanSerializeAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -93,6 +96,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<OuterComposite> Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -116,6 +120,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<decimal> Task FakeOuterNumberSerializeAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -139,6 +144,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> Task FakeOuterStringSerializeAsync(string body = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// Array of Enums /// @@ -160,6 +166,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<OuterEnum>> Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -183,18 +190,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null); - /// - /// - /// - /// - /// - /// - /// Thrown when fails to make API call - /// - /// - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); /// /// @@ -203,11 +198,25 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null); + Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null); + /// /// To test \"client\" model /// @@ -231,30 +240,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = 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. - /// Task<ApiResponse<object>> - Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -263,41 +248,48 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// 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> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = 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) - /// Header parameter enum test (string) (optional, default to -efg) - /// Query parameter enum test (string) (optional, default to -efg) - /// Form parameter enum test (string array) (optional, default to $) - /// Form parameter enum test (string) (optional, default to -efg) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null); /// /// To test enum parameters @@ -308,31 +300,34 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// Fake endpoint to test group parameters (optional) - /// - /// - /// Fake endpoint to test group parameters (optional) - /// - /// Thrown when fails to make API call - /// Required String in group parameters - /// Required Boolean in group parameters - /// Required Integer in group parameters - /// String in group parameters (optional) - /// Boolean in group parameters (optional) - /// Integer in group parameters (optional) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<object>> - Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null); /// /// Fake endpoint to test group parameters (optional) @@ -341,15 +336,33 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<object> - Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// test inline additionalProperties /// @@ -373,6 +386,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null); + /// /// test json serialization of form data /// @@ -398,6 +412,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null); + /// /// /// @@ -428,21 +443,19 @@ namespace Org.OpenAPITools.Api /// /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); } + Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeApi : IFakeApi + public partial class FakeApi : IApi.IFakeApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -499,6 +512,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Health check endpoint /// @@ -537,6 +559,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnFakeHealthGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterFakeHealthGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorFakeHealthGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Health check endpoint /// @@ -545,16 +595,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeHealthGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnFakeHealthGet(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/health"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -565,31 +620,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/health")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeHealthGet(apiResponse); + } return apiResponse; } @@ -597,7 +645,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeHealthGet(e, "/fake/health", uriBuilder.Path); throw; } } @@ -621,6 +669,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual bool? OnFakeOuterBooleanSerialize(bool? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterBooleanSerialize(ApiResponse apiResponse, bool? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterBooleanSerialize(Exception exception, string pathFormat, string path, bool? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer boolean types /// @@ -630,11 +709,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterBooleanSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -644,6 +726,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -653,7 +737,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -663,31 +747,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/boolean")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterBooleanSerialize(apiResponse, body); + } return apiResponse; } @@ -695,7 +772,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterBooleanSerialize(e, "/fake/outer/boolean", uriBuilder.Path, body); throw; } } @@ -740,6 +817,37 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual OuterComposite OnFakeOuterCompositeSerialize(OuterComposite outerComposite) + { + return outerComposite; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterCompositeSerialize(ApiResponse apiResponse, OuterComposite outerComposite) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterCompositeSerialize(Exception exception, string pathFormat, string path, OuterComposite outerComposite) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of object with outer number type /// @@ -749,11 +857,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + outerComposite = OnFakeOuterCompositeSerialize(outerComposite); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -763,6 +874,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(outerComposite, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -772,7 +885,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -782,31 +895,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/composite")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterCompositeSerialize(apiResponse, outerComposite); + } return apiResponse; } @@ -814,7 +920,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterCompositeSerialize(e, "/fake/outer/composite", uriBuilder.Path, outerComposite); throw; } } @@ -838,6 +944,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual decimal? OnFakeOuterNumberSerialize(decimal? body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterNumberSerialize(ApiResponse apiResponse, decimal? body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterNumberSerialize(Exception exception, string pathFormat, string path, decimal? body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer number types /// @@ -847,11 +984,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterNumberSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -861,6 +1001,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -870,7 +1012,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -880,31 +1022,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/number")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterNumberSerialize(apiResponse, body); + } return apiResponse; } @@ -912,7 +1047,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterNumberSerialize(e, "/fake/outer/number", uriBuilder.Path, body); throw; } } @@ -936,6 +1071,37 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnFakeOuterStringSerialize(string body) + { + return body; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFakeOuterStringSerialize(ApiResponse apiResponse, string body) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFakeOuterStringSerialize(Exception exception, string pathFormat, string path, string body) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Test serialization of outer string types /// @@ -945,11 +1111,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + body = OnFakeOuterStringSerialize(body); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -959,6 +1128,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(body, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -968,7 +1139,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "*/*" @@ -978,31 +1149,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/outer/string")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterFakeOuterStringSerialize(apiResponse, body); + } return apiResponse; } @@ -1010,7 +1174,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFakeOuterStringSerialize(e, "/fake/outer/string", uriBuilder.Path, body); throw; } } @@ -1053,6 +1217,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetArrayOfEnums() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetArrayOfEnums(ApiResponse> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetArrayOfEnums(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Array of Enums /// @@ -1061,16 +1253,21 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetArrayOfEnums(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/array-of-enums"; + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -1081,31 +1278,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/array-of-enums")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetArrayOfEnums(apiResponse); + } return apiResponse; } @@ -1113,7 +1303,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetArrayOfEnums(e, "/fake/array-of-enums", uriBuilder.Path); throw; } } @@ -1158,6 +1348,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual FileSchemaTestClass OnTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (fileSchemaTestClass == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return fileSchemaTestClass; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestBodyWithFileSchema(ApiResponse apiResponse, FileSchemaTestClass fileSchemaTestClass) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithFileSchema(Exception exception, string pathFormat, string path, FileSchemaTestClass fileSchemaTestClass) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// For this test, the body for this request much reference a schema named `File`. /// @@ -1167,18 +1397,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (fileSchemaTestClass == null) - throw new ArgumentNullException(nameof(fileSchemaTestClass)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + fileSchemaTestClass = OnTestBodyWithFileSchema(fileSchemaTestClass); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1188,6 +1414,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(fileSchemaTestClass, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1197,32 +1425,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("PUT"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-file-schema")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithFileSchema(apiResponse, fileSchemaTestClass); + } return apiResponse; } @@ -1230,7 +1451,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithFileSchema(e, "/fake/body-with-file-schema", uriBuilder.Path, fileSchemaTestClass); throw; } } @@ -1239,13 +1460,13 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1257,16 +1478,16 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> - public async Task TestBodyWithQueryParamsOrDefaultAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + result = await TestBodyWithQueryParamsWithHttpInfoAsync(user, query, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1277,31 +1498,72 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnTestBodyWithQueryParams(User user, string query) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (query == null) + throw new ArgumentNullException(nameof(query)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, query); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestBodyWithQueryParams(ApiResponse apiResponse, User user, string query) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestBodyWithQueryParams(Exception exception, string pathFormat, string path, User user, string query) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// /// /// Thrown when fails to make API call - /// /// + /// /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestBodyWithQueryParamsWithHttpInfoAsync(User user, string query, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (query == null) - throw new ArgumentNullException(nameof(query)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestBodyWithQueryParams(user, query); + user = validatedParameters.Item1; + query = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1317,6 +1579,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1326,32 +1590,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("PUT"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/body-with-query-params")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestBodyWithQueryParams(apiResponse, user, query); + } return apiResponse; } @@ -1359,7 +1616,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestBodyWithQueryParams(e, "/fake/body-with-query-params", uriBuilder.Path, user, query); throw; } } @@ -1404,6 +1661,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClientModel(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClientModel(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClientModel(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test \"client\" model To test \"client\" model /// @@ -1413,18 +1710,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClientModel(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1434,6 +1727,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1443,7 +1738,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1453,31 +1748,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("PATCH"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClientModel(apiResponse, modelClient); + } return apiResponse; } @@ -1485,7 +1773,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClientModel(e, "/fake", uriBuilder.Path, modelClient); throw; } } @@ -1494,25 +1782,25 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1524,28 +1812,28 @@ namespace Org.OpenAPITools.Api /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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. /// <> - public async Task TestEndpointParametersOrDefaultAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEndpointParametersOrDefaultAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + result = await TestEndpointParametersWithHttpInfoAsync(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1556,43 +1844,138 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (byte[], decimal, double, string, DateTime?, System.IO.Stream, float?, int?, int?, long?, string, string, string, DateTime?) OnTestEndpointParameters(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_byte == null) + throw new ArgumentNullException(nameof(_byte)); + + if (number == null) + throw new ArgumentNullException(nameof(number)); + + if (_double == null) + throw new ArgumentNullException(nameof(_double)); + + if (patternWithoutDelimiter == null) + throw new ArgumentNullException(nameof(patternWithoutDelimiter)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEndpointParameters(ApiResponse apiResponse, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEndpointParameters(Exception exception, string pathFormat, string path, byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date, System.IO.Stream binary, float? _float, int? integer, int? int32, long? int64, string _string, string password, string callback, DateTime? dateTime) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// /// Thrown when fails to make API call + /// None /// None /// None /// None - /// None + /// None (optional) + /// None (optional) + /// None (optional) /// 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> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEndpointParametersWithHttpInfoAsync(byte[] _byte, decimal number, double _double, string patternWithoutDelimiter, DateTime? date = null, System.IO.Stream binary = null, float? _float = null, int? integer = null, int? int32 = null, long? int64 = null, string _string = null, string password = null, string callback = null, DateTime? dateTime = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (patternWithoutDelimiter == null) - throw new ArgumentNullException(nameof(patternWithoutDelimiter)); - - if (_byte == null) - throw new ArgumentNullException(nameof(_byte)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestEndpointParameters(_byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + _byte = validatedParameters.Item1; + number = validatedParameters.Item2; + _double = validatedParameters.Item3; + patternWithoutDelimiter = validatedParameters.Item4; + date = validatedParameters.Item5; + binary = validatedParameters.Item6; + _float = validatedParameters.Item7; + integer = validatedParameters.Item8; + int32 = validatedParameters.Item9; + int64 = validatedParameters.Item10; + _string = validatedParameters.Item11; + password = validatedParameters.Item12; + callback = validatedParameters.Item13; + dateTime = validatedParameters.Item14; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1606,13 +1989,28 @@ namespace Org.OpenAPITools.Api multipartContent.Add(new FormUrlEncodedContent(formParams)); + formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + + + formParams.Add(new KeyValuePair("number", ClientUtils.ParameterToString(number))); + + formParams.Add(new KeyValuePair("double", ClientUtils.ParameterToString(_double))); + + formParams.Add(new KeyValuePair("pattern_without_delimiter", ClientUtils.ParameterToString(patternWithoutDelimiter))); - formParams.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(_byte))); + if (date != null) + formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); + + if (binary != null) + multipartContent.Add(new StreamContent(binary)); + + if (_float != null) + formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); if (integer != null) formParams.Add(new KeyValuePair("integer", ClientUtils.ParameterToString(integer))); @@ -1623,18 +2021,9 @@ namespace Org.OpenAPITools.Api if (int64 != null) formParams.Add(new KeyValuePair("int64", ClientUtils.ParameterToString(int64))); - if (_float != null) - formParams.Add(new KeyValuePair("float", ClientUtils.ParameterToString(_float))); - if (_string != null) formParams.Add(new KeyValuePair("string", ClientUtils.ParameterToString(_string))); - if (binary != null) - multipartContent.Add(new StreamContent(binary)); - - if (date != null) - formParams.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date))); - if (password != null) formParams.Add(new KeyValuePair("password", ClientUtils.ParameterToString(password))); @@ -1646,6 +2035,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BasicToken basicToken = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1661,32 +2052,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEndpointParameters(apiResponse, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1697,7 +2081,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEndpointParameters(e, "/fake", uriBuilder.Path, _byte, number, _double, patternWithoutDelimiter, date, binary, _float, integer, int32, int64, _string, password, callback, dateTime); throw; } } @@ -1708,17 +2092,17 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1732,20 +2116,20 @@ namespace Org.OpenAPITools.Api /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> - public async Task TestEnumParametersOrDefaultAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestEnumParametersOrDefaultAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryInteger, enumQueryDouble, enumHeaderString, enumQueryString, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + result = await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1756,27 +2140,90 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (List, List, double?, int?, List, string, string, string) OnTestEnumParameters(List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + return (enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestEnumParameters(ApiResponse apiResponse, List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestEnumParameters(Exception exception, string pathFormat, string path, List enumHeaderStringArray, List enumQueryStringArray, double? enumQueryDouble, int? enumQueryInteger, List enumFormStringArray, string enumHeaderString, string enumQueryString, string enumFormString) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// 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) + /// 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 array) (optional, default to $) /// Form parameter enum test (string) (optional, default to -efg) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string enumHeaderString = null, string enumQueryString = null, List enumFormStringArray = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = null, List enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + var validatedParameters = OnTestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + enumHeaderStringArray = validatedParameters.Item1; + enumQueryStringArray = validatedParameters.Item2; + enumQueryDouble = validatedParameters.Item3; + enumQueryInteger = validatedParameters.Item4; + enumFormStringArray = validatedParameters.Item5; + enumHeaderString = validatedParameters.Item6; + enumQueryString = validatedParameters.Item7; + enumFormString = validatedParameters.Item8; + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1786,12 +2233,12 @@ namespace Org.OpenAPITools.Api if (enumQueryStringArray != null) parseQueryString["enum_query_string_array"] = Uri.EscapeDataString(enumQueryStringArray.ToString()); - if (enumQueryInteger != null) - parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()); - if (enumQueryDouble != null) parseQueryString["enum_query_double"] = Uri.EscapeDataString(enumQueryDouble.ToString()); + if (enumQueryInteger != null) + parseQueryString["enum_query_integer"] = Uri.EscapeDataString(enumQueryInteger.ToString()); + if (enumQueryString != null) parseQueryString["enum_query_string"] = Uri.EscapeDataString(enumQueryString.ToString()); @@ -1809,14 +2256,14 @@ namespace Org.OpenAPITools.Api List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (enumFormStringArray != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (enumFormStringArray != null) formParams.Add(new KeyValuePair("enum_form_string_array", ClientUtils.ParameterToString(enumFormStringArray))); if (enumFormString != null) formParams.Add(new KeyValuePair("enum_form_string", ClientUtils.ParameterToString(enumFormString))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1826,32 +2273,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestEnumParameters(apiResponse, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } return apiResponse; } @@ -1859,7 +2299,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestEnumParameters(e, "/fake", uriBuilder.Path, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); throw; } } @@ -1868,17 +2308,17 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + ApiResponse result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1890,20 +2330,20 @@ namespace Org.OpenAPITools.Api /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// Boolean in group parameters (optional) + /// String in group parameters (optional) /// Integer in group parameters (optional) /// Cancellation Token to cancel the request. /// <> - public async Task TestGroupParametersOrDefaultAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + result = await TestGroupParametersWithHttpInfoAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1914,29 +2354,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual (bool, int, long, bool?, int?, long?) OnTestGroupParameters(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredBooleanGroup == null) + throw new ArgumentNullException(nameof(requiredBooleanGroup)); + + if (requiredStringGroup == null) + throw new ArgumentNullException(nameof(requiredStringGroup)); + + if (requiredInt64Group == null) + throw new ArgumentNullException(nameof(requiredInt64Group)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestGroupParameters(ApiResponse apiResponse, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestGroupParameters(Exception exception, string pathFormat, string path, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup, int? stringGroup, long? int64Group) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) /// /// Thrown when fails to make API call - /// Required String in group parameters /// Required Boolean in group parameters + /// Required String in group parameters /// Required Integer in group parameters - /// String in group parameters (optional) /// 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> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> TestGroupParametersWithHttpInfoAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool? booleanGroup = null, int? stringGroup = null, long? int64Group = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + requiredBooleanGroup = validatedParameters.Item1; + requiredStringGroup = validatedParameters.Item2; + requiredInt64Group = validatedParameters.Item3; + booleanGroup = validatedParameters.Item4; + stringGroup = validatedParameters.Item5; + int64Group = validatedParameters.Item6; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -1962,6 +2468,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; BearerToken bearerToken = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1972,28 +2480,21 @@ namespace Org.OpenAPITools.Api request.Method = new HttpMethod("DELETE"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestGroupParameters(apiResponse, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -2004,7 +2505,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestGroupParameters(e, "/fake", uriBuilder.Path, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); throw; } } @@ -2049,6 +2550,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Dictionary OnTestInlineAdditionalProperties(Dictionary requestBody) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return requestBody; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestInlineAdditionalProperties(ApiResponse apiResponse, Dictionary requestBody) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestInlineAdditionalProperties(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test inline additionalProperties /// @@ -2058,18 +2599,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requestBody == null) - throw new ArgumentNullException(nameof(requestBody)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + requestBody = OnTestInlineAdditionalProperties(requestBody); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2079,6 +2616,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2088,32 +2627,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/inline-additionalProperties")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestInlineAdditionalProperties(apiResponse, requestBody); + } return apiResponse; } @@ -2121,7 +2653,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestInlineAdditionalProperties(e, "/fake/inline-additionalProperties", uriBuilder.Path, requestBody); throw; } } @@ -2168,6 +2700,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnTestJsonFormData(string param, string param2) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (param == null) + throw new ArgumentNullException(nameof(param)); + + if (param2 == null) + throw new ArgumentNullException(nameof(param2)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (param, param2); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterTestJsonFormData(ApiResponse apiResponse, string param, string param2) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestJsonFormData(Exception exception, string pathFormat, string path, string param, string param2) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// test json serialization of form data /// @@ -2178,21 +2756,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (param == null) - throw new ArgumentNullException(nameof(param)); - - if (param2 == null) - throw new ArgumentNullException(nameof(param2)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestJsonFormData(param, param2); + param = validatedParameters.Item1; + param2 = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2208,8 +2781,12 @@ namespace Org.OpenAPITools.Api formParams.Add(new KeyValuePair("param", ClientUtils.ParameterToString(param))); + + formParams.Add(new KeyValuePair("param2", ClientUtils.ParameterToString(param2))); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -2219,32 +2796,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/jsonFormData")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestJsonFormData(apiResponse, param, param2); + } return apiResponse; } @@ -2252,7 +2822,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestJsonFormData(e, "/fake/jsonFormData", uriBuilder.Path, param, param2); throw; } } @@ -2305,6 +2875,70 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + protected virtual (List, List, List, List, List) OnTestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + 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)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (pipe, ioutil, http, url, context); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void AfterTestQueryParameterCollectionFormat(ApiResponse apiResponse, List pipe, List ioutil, List http, List url, List context) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorTestQueryParameterCollectionFormat(Exception exception, string pathFormat, string path, List pipe, List ioutil, List http, List url, List context) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test the collection format in query parameters /// @@ -2318,30 +2952,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - 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)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnTestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + pipe = validatedParameters.Item1; + ioutil = validatedParameters.Item2; + http = validatedParameters.Item3; + url = validatedParameters.Item4; + context = validatedParameters.Item5; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -2357,32 +2980,27 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; request.Method = new HttpMethod("PUT"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/test-query-parameters")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestQueryParameterCollectionFormat(apiResponse, pipe, ioutil, http, url, context); + } return apiResponse; } @@ -2390,8 +3008,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestQueryParameterCollectionFormat(e, "/fake/test-query-parameters", uriBuilder.Path, pipe, ioutil, http, url, context); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 4b51987ecd3..d7ae312c657 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IFakeClassnameTags123Api : IApi { @@ -48,21 +49,19 @@ namespace Org.OpenAPITools.Api /// client model /// Cancellation Token to cancel the request. /// Task of ApiResponse<ModelClient> - Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); } + Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + public partial class FakeClassnameTags123Api : IApi.IFakeClassnameTags123Api { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -119,6 +118,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -159,6 +167,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual ModelClient OnTestClassname(ModelClient modelClient) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return modelClient; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterTestClassname(ApiResponse apiResponse, ModelClient modelClient) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorTestClassname(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// To test class name in snake case To test class name in snake case /// @@ -168,26 +216,22 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (modelClient == null) - throw new ArgumentNullException(nameof(modelClient)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + modelClient = OnTestClassname(modelClient); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake_classname_test"; - System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); - request.Content = (modelClient as object) is System.IO.Stream stream + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); request.Content = (modelClient as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); @@ -210,7 +254,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -220,31 +264,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("PATCH"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake_classname_test")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterTestClassname(apiResponse, modelClient); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -255,8 +292,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorTestClassname(e, "/fake_classname_test", uriBuilder.Path, modelClient); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 00000000000..038f19bcfa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs index c8249afbb48..b858b1d8430 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IPetApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task AddPetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + /// /// Deletes a pet /// @@ -74,6 +76,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeletePetAsync(long petId, string apiKey = null, System.Threading.CancellationToken? cancellationToken = null); + /// /// Finds Pets by status /// @@ -97,6 +100,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken? cancellationToken = null); + /// /// Finds Pets by tags /// @@ -120,6 +124,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<List<Pet>> Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken? cancellationToken = null); + /// /// Find pet by ID /// @@ -143,6 +148,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Pet> Task GetPetByIdAsync(long petId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Update an existing pet /// @@ -166,6 +172,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null); + /// /// Updates a pet in the store with form data /// @@ -193,19 +200,6 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task UpdatePetWithFormAsync(long petId, string name = null, string status = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server (optional) - /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task<ApiResponse<ApiResponse>> - Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image @@ -215,24 +209,25 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) - /// Cancellation Token to cancel the request. - /// Task of ApiResponse<ApiResponse> - Task UploadFileAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null); - /// - /// uploads an image (required) - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// file to upload /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task<ApiResponse<ApiResponse>> - Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = 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. + /// Task of ApiResponse<ApiResponse> + Task UploadFileAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); /// /// uploads an image (required) @@ -241,26 +236,38 @@ namespace Org.OpenAPITools.Api /// /// /// Thrown when fails to make API call - /// ID of pet to update /// 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> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = 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. /// Task of ApiResponse<ApiResponse> - Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); } + Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class PetApi : IPetApi + public partial class PetApi : IApi.IPetApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -317,6 +324,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Add a new pet to the store /// @@ -357,6 +373,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnAddPet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterAddPet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorAddPet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Add a new pet to the store /// @@ -366,22 +422,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> AddPetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnAddPet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress.Host; - uriBuilder.Port = HttpClient.BaseAddress.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -389,6 +441,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -413,32 +467,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterAddPet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -452,7 +499,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorAddPet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -499,6 +546,49 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (long, string) OnDeletePet(long petId, string apiKey) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, apiKey); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterDeletePet(ApiResponse apiResponse, long petId, string apiKey) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorDeletePet(Exception exception, string pathFormat, string path, long petId, string apiKey) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Deletes a pet /// @@ -509,26 +599,28 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnDeletePet(petId, apiKey); + petId = validatedParameters.Item1; + apiKey = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - if (apiKey != null) + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); if (apiKey != null) request.Headers.Add("api_key", ClientUtils.ParameterToString(apiKey)); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -539,28 +631,21 @@ namespace Org.OpenAPITools.Api request.Method = new HttpMethod("DELETE"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeletePet(apiResponse, petId, apiKey); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -571,7 +656,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeletePet(e, "/pet/{petId}", uriBuilder.Path, petId, apiKey); throw; } } @@ -616,6 +701,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByStatus(List status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (status == null) + throw new ArgumentNullException(nameof(status)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return status; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByStatus(ApiResponse> apiResponse, List status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByStatus(Exception exception, string pathFormat, string path, List status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by status Multiple status values can be provided with comma separated strings /// @@ -625,18 +750,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> FindPetsByStatusWithHttpInfoAsync(List status, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (status == null) - throw new ArgumentNullException(nameof(status)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + status = OnFindPetsByStatus(status); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -650,6 +771,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -675,31 +798,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByStatus")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByStatus(apiResponse, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -713,7 +829,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByStatus(e, "/pet/findByStatus", uriBuilder.Path, status); throw; } } @@ -758,6 +874,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnFindPetsByTags(List tags) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return tags; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterFindPetsByTags(ApiResponse> apiResponse, List tags) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorFindPetsByTags(Exception exception, string pathFormat, string path, List tags) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @@ -767,18 +923,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> FindPetsByTagsWithHttpInfoAsync(List tags, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (tags == null) - throw new ArgumentNullException(nameof(tags)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + tags = OnFindPetsByTags(tags); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -792,6 +944,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -817,31 +971,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/findByTags")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterFindPetsByTags(apiResponse, tags); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -855,7 +1002,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorFindPetsByTags(e, "/pet/findByTags", uriBuilder.Path, tags); throw; } } @@ -900,6 +1047,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetPetById(long petId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return petId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetPetById(ApiResponse apiResponse, long petId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetPetById(Exception exception, string pathFormat, string path, long petId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find pet by ID Returns a single pet /// @@ -909,22 +1096,20 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetPetByIdWithHttpInfoAsync(long petId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + petId = OnGetPetById(petId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokens = new List(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); List tokens = new List(); ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -943,31 +1128,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetPetById(apiResponse, petId); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -978,7 +1156,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetPetById(e, "/pet/{petId}", uriBuilder.Path, petId); throw; } } @@ -1023,6 +1201,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Pet OnUpdatePet(Pet pet) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return pet; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterUpdatePet(ApiResponse apiResponse, Pet pet) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePet(Exception exception, string pathFormat, string path, Pet pet) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Update an existing pet /// @@ -1032,22 +1250,18 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (pet == null) - throw new ArgumentNullException(nameof(pet)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + pet = OnUpdatePet(pet); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); - uriBuilder.Host = HttpClient.BaseAddress.Host; - uriBuilder.Port = HttpClient.BaseAddress.Port; - uriBuilder.Scheme = ClientUtils.SCHEME; - uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet"; + var url = request.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; request.Content = (pet as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) @@ -1055,6 +1269,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; HttpSignatureToken signatureToken = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1079,32 +1295,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("PUT"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePet(apiResponse, pet); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1118,7 +1327,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePet(e, "/pet", uriBuilder.Path, pet); throw; } } @@ -1167,6 +1376,52 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, string, string) OnUpdatePetWithForm(long petId, string name, string status) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, name, status); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUpdatePetWithForm(ApiResponse apiResponse, long petId, string name, string status) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdatePetWithForm(Exception exception, string pathFormat, string path, long petId, string name, string status) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updates a pet in the store with form data /// @@ -1178,30 +1433,29 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = null, string status = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdatePetWithForm(petId, name, status); + petId = validatedParameters.Item1; + name = validatedParameters.Item2; + status = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - if (name != null) + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (name != null) formParams.Add(new KeyValuePair("name", ClientUtils.ParameterToString(name))); if (status != null) @@ -1209,6 +1463,8 @@ namespace Org.OpenAPITools.Api List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1224,32 +1480,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdatePetWithForm(apiResponse, petId, name, status); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1260,7 +1509,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdatePetWithForm(e, "/pet/{petId}", uriBuilder.Path, petId, name, status); throw; } } @@ -1270,13 +1519,13 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1289,16 +1538,16 @@ namespace Org.OpenAPITools.Api /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileOrDefaultAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileOrDefaultAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithHttpInfoAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1309,48 +1558,95 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (long, System.IO.Stream, string) OnUploadFile(long petId, System.IO.Stream file, string additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (petId, file, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFile(ApiResponse apiResponse, long petId, System.IO.Stream file, string additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFile(Exception exception, string pathFormat, string path, long petId, System.IO.Stream file, string additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image /// /// Thrown when fails to make API call /// ID of pet to update - /// Additional data to pass to server (optional) /// file to upload (optional) + /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = null, System.IO.Stream file = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithHttpInfoAsync(long petId, System.IO.Stream file = null, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFile(petId, file, additionalMetadata); + petId = validatedParameters.Item1; + file = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}/uploadImage"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); if (file != null) + multipartContent.Add(new StreamContent(file)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); - if (file != null) - multipartContent.Add(new StreamContent(file)); - List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1366,7 +1662,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json" @@ -1376,31 +1672,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/pet/{petId}/uploadImage")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFile(apiResponse, petId, file, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1411,7 +1700,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFile(e, "/pet/{petId}/uploadImage", uriBuilder.Path, petId, file, additionalMetadata); throw; } } @@ -1420,14 +1709,14 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1439,17 +1728,17 @@ namespace Org.OpenAPITools.Api /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// file to upload + /// ID of pet to update /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// <> - public async Task UploadFileWithRequiredFileOrDefaultAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + result = await UploadFileWithRequiredFileWithHttpInfoAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1460,50 +1749,97 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + protected virtual (System.IO.Stream, long, string) OnUploadFileWithRequiredFile(System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (requiredFile == null) + throw new ArgumentNullException(nameof(requiredFile)); + + if (petId == null) + throw new ArgumentNullException(nameof(petId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (requiredFile, petId, additionalMetadata); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void AfterUploadFileWithRequiredFile(ApiResponse apiResponse, System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUploadFileWithRequiredFile(Exception exception, string pathFormat, string path, System.IO.Stream requiredFile, long petId, string additionalMetadata) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// uploads an image (required) /// /// Thrown when fails to make API call - /// ID of pet to update /// 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> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UploadFileWithRequiredFileWithHttpInfoAsync(System.IO.Stream requiredFile, long petId, string additionalMetadata = null, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (requiredFile == null) - throw new ArgumentNullException(nameof(requiredFile)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); + requiredFile = validatedParameters.Item1; + petId = validatedParameters.Item2; + additionalMetadata = validatedParameters.Item3; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/fake/{petId}/uploadImageWithRequiredFile"; - uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - MultipartContent multipartContent = new MultipartContent(); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); MultipartContent multipartContent = new MultipartContent(); request.Content = multipartContent; List> formParams = new List>(); - multipartContent.Add(new FormUrlEncodedContent(formParams)); - - multipartContent.Add(new StreamContent(requiredFile)); + multipartContent.Add(new FormUrlEncodedContent(formParams)); multipartContent.Add(new StreamContent(requiredFile)); if (additionalMetadata != null) formParams.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata))); List tokens = new List(); + + request.RequestUri = uriBuilder.Uri; OAuthToken oauthToken = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); @@ -1519,7 +1855,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/json", @@ -1530,31 +1866,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/fake/{petId}/uploadImageWithRequiredFile")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUploadFileWithRequiredFile(apiResponse, requiredFile, petId, additionalMetadata); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -1565,8 +1894,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUploadFileWithRequiredFile(e, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilder.Path, requiredFile, petId, additionalMetadata); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs index a0be4ccdafb..07af6e52b76 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IStoreApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Returns pet inventories by status /// @@ -70,6 +72,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Dictionary<string, int>> Task> GetInventoryAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// Find purchase order by ID /// @@ -93,6 +96,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null); + /// /// Place an order for a pet /// @@ -115,21 +119,19 @@ namespace Org.OpenAPITools.Api /// order placed for purchasing the pet /// Cancellation Token to cancel the request. /// Task of ApiResponse<Order> - Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); } + Task PlaceOrderAsync(Order order, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class StoreApi : IStoreApi + public partial class StoreApi : IApi.IStoreApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -186,6 +188,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -226,6 +237,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteOrder(string orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteOrder(ApiResponse apiResponse, string orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteOrder(Exception exception, string pathFormat, string path, string orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -235,50 +286,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteOrderWithHttpInfoAsync(string orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (orderId == null) - throw new ArgumentNullException(nameof(orderId)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnDeleteOrder(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = new HttpMethod("DELETE"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteOrder(apiResponse, orderId); + } return apiResponse; } @@ -286,7 +327,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteOrder(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -309,6 +350,34 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnGetInventory() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterGetInventory(ApiResponse> apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorGetInventory(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// @@ -317,11 +386,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task>> GetInventoryWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnGetInventory(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -345,31 +417,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse> apiResponse = new ApiResponse>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize>(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetInventory(apiResponse); + } else if (apiResponse.StatusCode == (HttpStatusCode) 429) foreach(TokenBase token in tokens) token.BeginRateLimit(); @@ -380,7 +445,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetInventory(e, "/store/inventory", uriBuilder.Path); throw; } } @@ -425,6 +490,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual long OnGetOrderById(long orderId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return orderId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetOrderById(ApiResponse apiResponse, long orderId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetOrderById(Exception exception, string pathFormat, string path, long orderId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions /// @@ -434,19 +539,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetOrderByIdWithHttpInfoAsync(long orderId, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + orderId = OnGetOrderById(orderId); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); request.RequestUri = uriBuilder.Uri; @@ -460,31 +565,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order/{order_id}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetOrderById(apiResponse, orderId); + } return apiResponse; } @@ -492,7 +590,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetOrderById(e, "/store/order/{order_id}", uriBuilder.Path, orderId); throw; } } @@ -537,6 +635,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual Order OnPlaceOrder(Order order) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (order == null) + throw new ArgumentNullException(nameof(order)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return order; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterPlaceOrder(ApiResponse apiResponse, Order order) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorPlaceOrder(Exception exception, string pathFormat, string path, Order order) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Place an order for a pet /// @@ -546,18 +684,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> PlaceOrderWithHttpInfoAsync(Order order, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (order == null) - throw new ArgumentNullException(nameof(order)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + order = OnPlaceOrder(order); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -567,6 +701,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(order, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -576,7 +712,7 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); string[] accepts = new string[] { "application/xml", @@ -587,31 +723,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/order")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterPlaceOrder(apiResponse, order); + } return apiResponse; } @@ -619,8 +748,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorPlaceOrder(e, "/store/order", uriBuilder.Path, order); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs index 554608a79aa..88d04ddaf5d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -19,10 +19,11 @@ using System.Text.Json; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Api +namespace Org.OpenAPITools.IApi { /// /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. /// public interface IUserApi : IApi { @@ -49,6 +50,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUserAsync(User user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Creates list of users with given input array /// @@ -72,6 +74,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Creates list of users with given input array /// @@ -95,6 +98,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken? cancellationToken = null); + /// /// Delete user /// @@ -118,6 +122,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task DeleteUserAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + /// /// Get user by user name /// @@ -141,6 +146,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<User> Task GetUserByNameAsync(string username, System.Threading.CancellationToken? cancellationToken = null); + /// /// Logs user into the system /// @@ -166,6 +172,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<string> Task LoginUserAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null); + /// /// Logs out current logged in user session /// @@ -187,6 +194,7 @@ namespace Org.OpenAPITools.Api /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> Task LogoutUserAsync(System.Threading.CancellationToken? cancellationToken = null); + /// /// Updated user /// @@ -194,11 +202,11 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task<ApiResponse<object>> - Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); + Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); /// /// Updated user @@ -207,25 +215,23 @@ namespace Org.OpenAPITools.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// Task of ApiResponse<object> - Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null); } + Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null); + } +} +namespace Org.OpenAPITools.Api +{ /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class UserApi : IUserApi + public partial class UserApi : IApi.IUserApi { private JsonSerializerOptions _jsonSerializerOptions; - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - public event ClientUtils.EventHandler ApiResponded; - /// /// The logger /// @@ -282,6 +288,15 @@ namespace Org.OpenAPITools.Api OauthTokenProvider = oauthTokenProvider; } + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + /// /// Create user This can only be done by the logged in user. /// @@ -322,6 +337,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual User OnCreateUser(User user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUser(ApiResponse apiResponse, User user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUser(Exception exception, string pathFormat, string path, User user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Create user This can only be done by the logged in user. /// @@ -331,18 +386,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUserWithHttpInfoAsync(User user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUser(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -352,6 +403,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -361,32 +414,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUser(apiResponse, user); + } return apiResponse; } @@ -394,7 +440,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUser(e, "/user", uriBuilder.Path, user); throw; } } @@ -439,6 +485,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithArrayInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithArrayInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithArrayInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -448,18 +534,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithArrayInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -469,6 +551,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -478,32 +562,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithArray")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithArrayInput(apiResponse, user); + } return apiResponse; } @@ -511,7 +588,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithArrayInput(e, "/user/createWithArray", uriBuilder.Path, user); throw; } } @@ -556,6 +633,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual List OnCreateUsersWithListInput(List user) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return user; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterCreateUsersWithListInput(ApiResponse apiResponse, List user) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorCreateUsersWithListInput(Exception exception, string pathFormat, string path, List user) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Creates list of users with given input array /// @@ -565,18 +682,14 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> CreateUsersWithListInputWithHttpInfoAsync(List user, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + user = OnCreateUsersWithListInput(user); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -586,6 +699,8 @@ namespace Org.OpenAPITools.Api ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -595,32 +710,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("POST"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/createWithList")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterCreateUsersWithListInput(apiResponse, user); + } return apiResponse; } @@ -628,7 +736,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorCreateUsersWithListInput(e, "/user/createWithList", uriBuilder.Path, user); throw; } } @@ -673,6 +781,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnDeleteUser(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterDeleteUser(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorDeleteUser(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Delete user This can only be done by the logged in user. /// @@ -682,50 +830,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> DeleteUserWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnDeleteUser(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; request.Method = new HttpMethod("DELETE"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterDeleteUser(apiResponse, username); + } return apiResponse; } @@ -733,7 +871,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorDeleteUser(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -778,6 +916,46 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnGetUserByName(string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return username; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterGetUserByName(ApiResponse apiResponse, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorGetUserByName(Exception exception, string pathFormat, string path, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Get user by user name /// @@ -787,22 +965,19 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> GetUserByNameWithHttpInfoAsync(string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + username = OnGetUserByName(username); using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.RequestUri = uriBuilder.Uri; @@ -816,31 +991,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterGetUserByName(apiResponse, username); + } return apiResponse; } @@ -848,7 +1016,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorGetUserByName(e, "/user/{username}", uriBuilder.Path, username); throw; } } @@ -873,6 +1041,52 @@ namespace Org.OpenAPITools.Api return result.Content; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (string, string) OnLoginUser(string username, string password) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + if (password == null) + throw new ArgumentNullException(nameof(password)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (username, password); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterLoginUser(ApiResponse apiResponse, string username, string password) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorLoginUser(Exception exception, string pathFormat, string path, string username, string password) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs user into the system /// @@ -883,21 +1097,16 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LoginUserWithHttpInfoAsync(string username, string password, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (password == null) - throw new ArgumentNullException(nameof(password)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnLoginUser(username, password); + username = validatedParameters.Item1; + password = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; @@ -910,6 +1119,8 @@ namespace Org.OpenAPITools.Api uriBuilder.Query = parseQueryString.ToString(); + + request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { @@ -921,31 +1132,24 @@ namespace Org.OpenAPITools.Api if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); - + request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/login")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLoginUser(apiResponse, username, password); + } return apiResponse; } @@ -953,7 +1157,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLoginUser(e, "/user/login", uriBuilder.Path, username, password); throw; } } @@ -996,6 +1200,34 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + protected virtual void OnLogoutUser() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterLogoutUser(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorLogoutUser(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Logs out current logged in user session /// @@ -1004,42 +1236,40 @@ namespace Org.OpenAPITools.Api /// <> where T : public async Task> LogoutUserWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { + OnLogoutUser(); + using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/logout"; + + request.RequestUri = uriBuilder.Uri; request.Method = new HttpMethod("GET"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/logout")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterLogoutUser(apiResponse); + } return apiResponse; } @@ -1047,7 +1277,7 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorLogoutUser(e, "/user/logout", uriBuilder.Path); throw; } } @@ -1056,13 +1286,13 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { - ApiResponse result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + ApiResponse result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); if (result.Content == null) throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); @@ -1074,16 +1304,16 @@ namespace Org.OpenAPITools.Api /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> - public async Task UpdateUserOrDefaultAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { ApiResponse result = null; try { - result = await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + result = await UpdateUserWithHttpInfoAsync(user, username, cancellationToken).ConfigureAwait(false); } catch (Exception) { @@ -1094,41 +1324,83 @@ namespace Org.OpenAPITools.Api : null; } + /// + /// Validates the request parameters + /// + /// + /// + /// + protected virtual (User, string) OnUpdateUser(User user, string username) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (username == null) + throw new ArgumentNullException(nameof(username)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return (user, username); + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void AfterUpdateUser(ApiResponse apiResponse, User user, string username) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + protected virtual void OnErrorUpdateUser(Exception exception, string pathFormat, string path, User user, string username) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + /// /// Updated user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// name that need to be deleted /// Updated user object + /// name that need to be deleted /// Cancellation Token to cancel the request. /// <> where T : - public async Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken? cancellationToken = null) + public async Task> UpdateUserWithHttpInfoAsync(User user, string username, System.Threading.CancellationToken? cancellationToken = null) { + UriBuilder uriBuilder = new UriBuilder(); + try { - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' - - if (username == null) - throw new ArgumentNullException(nameof(username)); - - if (user == null) - throw new ArgumentNullException(nameof(user)); - - #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + var validatedParameters = OnUpdateUser(user, username); + user = validatedParameters.Item1; + username = validatedParameters.Item2; using (HttpRequestMessage request = new HttpRequestMessage()) { - UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Port = HttpClient.BaseAddress.Port; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; - uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); - request.Content = (user as object) is System.IO.Stream stream + uriBuilder.Path = uriBuilder.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); request.Content = (user as object) is System.IO.Stream stream ? request.Content = new StreamContent(stream) : request.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { @@ -1138,32 +1410,25 @@ namespace Org.OpenAPITools.Api string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) - request.Content.Headers.Add("ContentType", contentType); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Method = new HttpMethod("PUT"); + DateTime requestedAt = DateTime.UtcNow; + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { - DateTime requestedAt = DateTime.UtcNow; + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}", uriBuilder.Path)); string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); - if (ApiResponded != null) - { - try - { - ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/user/{username}")); - } - catch(Exception e) - { - Logger.LogError(e, "An error occurred while invoking ApiResponded."); - } - } - ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) + { apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterUpdateUser(apiResponse, user, username); + } return apiResponse; } @@ -1171,8 +1436,9 @@ namespace Org.OpenAPITools.Api } catch(Exception e) { - Logger.LogError(e, "An error occurred while sending the request to the server."); + OnErrorUpdateUser(e, "/user/{username}", uriBuilder.Path, user, username); throw; } - } } + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 00000000000..7757b89c191 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.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.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs index f63fd593329..5cc9c254920 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -16,22 +16,12 @@ namespace Org.OpenAPITools.Client /// /// /// - /// + /// public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { _raw = $"{ prefix }{ value }"; } - /// - /// Places the token in the cookie. - /// - /// - /// - public virtual void UseInCookie(System.Net.Http.HttpRequestMessage request, string cookieName) - { - request.Headers.Add("Cookie", $"{ cookieName }=_raw"); - } - /// /// Places the token in the header. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs index e5da6000321..f87e53e8b04 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -12,35 +12,46 @@ namespace Org.OpenAPITools.Client /// The time the request was sent. /// public DateTime RequestedAt { get; } + /// /// The time the response was received. /// public DateTime ReceivedAt { get; } + /// /// The HttpStatusCode received. /// public HttpStatusCode HttpStatus { get; } + /// /// The path requested. /// - public string Path { get; } + public string PathFormat { get; } + /// /// The elapsed time from request to response. /// public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + /// + /// The path + /// + public string Path { get; } + /// /// The event args used to track server health. /// /// /// /// + /// /// - public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string path) + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) { RequestedAt = requestedAt; ReceivedAt = receivedAt; HttpStatus = httpStatus; + PathFormat = pathFormat; Path = path; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs index 3bae0aaa6ab..0a8a0769c19 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -34,6 +34,11 @@ namespace Org.OpenAPITools.Client /// The raw content of this response /// string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } } /// @@ -41,12 +46,10 @@ namespace Org.OpenAPITools.Client /// public partial class ApiResponse : IApiResponse { - #region Properties - /// /// The deserialized content /// - public T Content { get; set; } + public T Content { get; internal set; } /// /// Gets or sets the status code (HTTP status code) @@ -82,7 +85,10 @@ namespace Org.OpenAPITools.Client /// public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } - #endregion Properties + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; /// /// Construct the response using an HttpResponseMessage diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs index 8be839fed64..a6ecdf11c02 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -10,16 +10,9 @@ using System; using System.IO; using System.Linq; -using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Polly.Timeout; -using Polly.Extensions.Http; -using Polly; -using Org.OpenAPITools.Api; using KellermanSoftware.CompareNetObjects; namespace Org.OpenAPITools.Client @@ -280,114 +273,5 @@ namespace Org.OpenAPITools.Client /// The format to use for DateTime serialization /// public const string ISO8601_DATETIME_FORMAT = "o"; - - /// - /// 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, config); - - AddApi(services, config); - }); - - return builder; - } - - /// - /// Add the api to your host builder. - /// - /// - /// - public static void AddApi(this IServiceCollection services, Action options) - { - HostConfiguration config = new HostConfiguration(services); - options(config); - AddApi(services, config); - } - - private static void AddApi(IServiceCollection services, HostConfiguration host) - { - if (!host.HttpClientsAdded) - host.AddApiHttpClients(); - - // 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))); - } - } - } - - /// - /// 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 circiut 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 00000000000..da94287dab8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,18 @@ +// + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 00000000000..47daa5b77e5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * 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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 00000000000..02d9e10ba7e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.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 Org.OpenAPITools.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 + { + public static readonly string[] FORMATS = { + "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", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// 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(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs index e3200ba2391..49dd0278de5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -14,7 +14,6 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Net.Http; using Microsoft.Extensions.DependencyInjection; -using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client @@ -22,10 +21,17 @@ namespace Org.OpenAPITools.Client /// /// Provides hosting configuration for Org.OpenAPITools /// - public class HostConfiguration + public class HostConfiguration + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi { private readonly IServiceCollection _services; - private JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); internal bool HttpClientsAdded { get; private set; } @@ -37,35 +43,101 @@ namespace Org.OpenAPITools.Client { _services = services; _jsonOptions.Converters.Add(new JsonStringEnumConverter()); - _jsonOptions.Converters.Add(new OpenAPIDateJsonConverter()); + _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 CatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new CategoryJsonConverter()); _jsonOptions.Converters.Add(new ChildCatJsonConverter()); + _jsonOptions.Converters.Add(new ChildCatAllOfJsonConverter()); + _jsonOptions.Converters.Add(new ClassModelJsonConverter()); _jsonOptions.Converters.Add(new ComplexQuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new DanishPigJsonConverter()); + _jsonOptions.Converters.Add(new DeprecatedObjectJsonConverter()); _jsonOptions.Converters.Add(new DogJsonConverter()); + _jsonOptions.Converters.Add(new DogAllOfJsonConverter()); + _jsonOptions.Converters.Add(new DrawingJsonConverter()); + _jsonOptions.Converters.Add(new EnumArraysJsonConverter()); + _jsonOptions.Converters.Add(new EnumClassConverter()); + _jsonOptions.Converters.Add(new EnumClassNullableConverter()); + _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 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 NullableClassJsonConverter()); _jsonOptions.Converters.Add(new NullableShapeJsonConverter()); + _jsonOptions.Converters.Add(new NumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ObjectWithDeprecatedFieldsJsonConverter()); + _jsonOptions.Converters.Add(new OrderJsonConverter()); + _jsonOptions.Converters.Add(new OuterCompositeJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumConverter()); + _jsonOptions.Converters.Add(new OuterEnumNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerNullableConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueNullableConverter()); _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 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 TriangleJsonConverter()); + _jsonOptions.Converters.Add(new TriangleInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new WhaleJsonConverter()); + _jsonOptions.Converters.Add(new ZebraJsonConverter()); _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); - _services.AddSingleton(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); + _services.AddTransient(); } /// @@ -74,29 +146,22 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddApiHttpClients + public HostConfiguration AddApiHttpClients ( Action client = null, Action builder = null) - where TAnotherFakeApi : class, IAnotherFakeApi - where TDefaultApi : class, IDefaultApi - where TFakeApi : class, IFakeApi - where TFakeClassnameTags123Api : class, IFakeClassnameTags123Api - where TPetApi : class, IPetApi - where TStoreApi : class, IStoreApi - where TUserApi : class, IUserApi { 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)); + + 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) @@ -107,25 +172,12 @@ namespace Org.OpenAPITools.Client return this; } - /// - /// Configures the HttpClients. - /// - /// - /// - /// - public HostConfiguration AddApiHttpClients(Action client = null, Action builder = null) - { - AddApiHttpClients(client, builder); - - return this; - } - /// /// Configures the JsonSerializerSettings /// /// /// - public HostConfiguration ConfigureJsonOptions(Action options) + public HostConfiguration ConfigureJsonOptions(Action options) { options(_jsonOptions); @@ -138,7 +190,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase { return AddTokens(new TTokenBase[]{ token }); } @@ -149,7 +201,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase { TokenContainer container = new TokenContainer(tokens); _services.AddSingleton(services => container); @@ -163,7 +215,7 @@ namespace Org.OpenAPITools.Client /// /// /// - public HostConfiguration UseProvider() + public HostConfiguration UseProvider() where TTokenProvider : TokenProvider where TTokenBase : TokenBase { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/IApi.cs deleted file mode 100644 index bd74ad34fd3..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/IApi.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Net.Http; - -namespace Org.OpenAPITools.Client -{ - /// - /// Any Api client - /// - public interface IApi - { - /// - /// The HttpClient - /// - HttpClient HttpClient { get; } - - /// - /// An event to track the health of the server. - /// If you store these event args, be sure to purge old event args to prevent a memory leak. - /// - event ClientUtils.EventHandler ApiResponded; - } -} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs deleted file mode 100644 index a280076c5a9..00000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 Org.OpenAPITools.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 OpenAPIDateJsonConverter : JsonConverter - { - /// - /// Returns a DateTime from the Json object - /// - /// - /// - /// - /// - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => - DateTime.ParseExact(reader.GetString(), "yyyy-MM-dd", CultureInfo.InvariantCulture); - - /// - /// Writes the DateTime to the json writer - /// - /// - /// - /// - public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => - writer.WriteStringValue(dateTimeValue.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); - } -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 00000000000..deefb4ab70e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,57 @@ +/* + * 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.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 00000000000..a204267fa64 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.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.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.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 circiut 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 00000000000..b7cfb5f6f9c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,88 @@ +/* + * 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.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.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) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TAnotherFakeApi : class, IApi.IAnotherFakeApi + where TDefaultApi : class, IApi.IDefaultApi + where TFakeApi : class, IApi.IFakeApi + where TFakeClassnameTags123Api : class, IApi.IFakeClassnameTags123Api + where TPetApi : class, IApi.IPetApi + where TStoreApi : class, IApi.IStoreApi + where TUserApi : class, IApi.IUserApi + { + 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-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs index 68647a4ae15..35452f5ff88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// test map of maps /// - public partial class Activity : IEquatable, IValidatableObject + public partial class Activity : IValidatableObject { /// /// Initializes a new instance of the class. /// /// activityOutputs - public Activity(Dictionary> activityOutputs = default) + [JsonConstructor] + public Activity(Dictionary> activityOutputs) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (activityOutputs == null) + throw new ArgumentNullException("activityOutputs is a required property for Activity and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ActivityOutputs = activityOutputs; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 Activity).AreEqual; - } - - /// - /// Returns true if Activity instances are equal - /// - /// Instance of Activity to be compared - /// Boolean - public bool Equals(Activity 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; - if (this.ActivityOutputs != null) - { - hashCode = (hashCode * 59) + this.ActivityOutputs.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Activity + /// + public class ActivityJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Activity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary> activityOutputs = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "activity_outputs": + activityOutputs = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new Activity(activityOutputs); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Activity activity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index ed290bab607..31ae89912fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// ActivityOutputElementRepresentation /// - public partial class ActivityOutputElementRepresentation : IEquatable, IValidatableObject + public partial class ActivityOutputElementRepresentation : IValidatableObject { /// /// Initializes a new instance of the class. /// /// prop1 /// prop2 - public ActivityOutputElementRepresentation(string prop1 = default, Object prop2 = default) + [JsonConstructor] + public ActivityOutputElementRepresentation(string prop1, Object prop2) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (prop1 == null) + throw new ArgumentNullException("prop1 is a required property for ActivityOutputElementRepresentation and cannot be null."); + + if (prop2 == null) + throw new ArgumentNullException("prop2 is a required property for ActivityOutputElementRepresentation and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Prop1 = prop1; Prop2 = prop2; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 ActivityOutputElementRepresentation).AreEqual; - } - - /// - /// Returns true if ActivityOutputElementRepresentation instances are equal - /// - /// Instance of ActivityOutputElementRepresentation to be compared - /// Boolean - public bool Equals(ActivityOutputElementRepresentation 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; - if (this.Prop1 != null) - { - hashCode = (hashCode * 59) + this.Prop1.GetHashCode(); - } - if (this.Prop2 != null) - { - hashCode = (hashCode * 59) + this.Prop2.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,77 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ActivityOutputElementRepresentation + /// + public class ActivityOutputElementRepresentationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string prop1 = default; + Object prop2 = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "prop1": + prop1 = reader.GetString(); + break; + case "prop2": + prop2 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new ActivityOutputElementRepresentation(prop1, prop2); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 25b11f890fa..5682c09e840 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,36 +26,65 @@ namespace Org.OpenAPITools.Model /// /// AdditionalPropertiesClass /// - public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class AdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty - /// anytype1 + /// mapProperty /// mapWithUndeclaredPropertiesAnytype1 /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 - /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapWithUndeclaredPropertiesString - public AdditionalPropertiesClass(Dictionary mapProperty = default, Dictionary> mapOfMapProperty = default, Object anytype1 = default, Object mapWithUndeclaredPropertiesAnytype1 = default, Object mapWithUndeclaredPropertiesAnytype2 = default, Dictionary mapWithUndeclaredPropertiesAnytype3 = default, Object emptyMap = default, Dictionary mapWithUndeclaredPropertiesString = default) + /// anytype1 + [JsonConstructor] + public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object anytype1 = default) { - MapProperty = mapProperty; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapProperty == null) + throw new ArgumentNullException("mapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapOfMapProperty == null) + throw new ArgumentNullException("mapOfMapProperty is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype1 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype2 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesAnytype3 is a required property for AdditionalPropertiesClass and cannot be null."); + + if (emptyMap == null) + throw new ArgumentNullException("emptyMap is a required property for AdditionalPropertiesClass and cannot be null."); + + if (mapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException("mapWithUndeclaredPropertiesString is a required property for AdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + EmptyMap = emptyMap; MapOfMapProperty = mapOfMapProperty; - Anytype1 = anytype1; + MapProperty = mapProperty; MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - EmptyMap = emptyMap; MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + Anytype1 = anytype1; } /// - /// Gets or Sets MapProperty + /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// - [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + /// 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 @@ -65,10 +93,10 @@ namespace Org.OpenAPITools.Model public Dictionary> MapOfMapProperty { get; set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapProperty /// - [JsonPropertyName("anytype_1")] - public Object Anytype1 { get; set; } + [JsonPropertyName("map_property")] + public Dictionary MapProperty { get; set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 @@ -88,24 +116,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("map_with_undeclared_properties_anytype_3")] public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } - /// - /// 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 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -115,88 +142,18 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); - sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).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(" EmptyMap: ").Append(EmptyMap).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesClass instances are equal - /// - /// Instance of AdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(AdditionalPropertiesClass 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; - if (this.MapProperty != null) - { - hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); - } - if (this.MapOfMapProperty != null) - { - hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); - } - if (this.Anytype1 != null) - { - hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype1 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype2 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesAnytype3 != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); - } - if (this.EmptyMap != null) - { - hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); - } - if (this.MapWithUndeclaredPropertiesString != null) - { - hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -208,4 +165,114 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AdditionalPropertiesClass + /// + public class AdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "empty_map": + emptyMap = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_of_map_property": + mapOfMapProperty = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_property": + mapProperty = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_1": + mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_2": + mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref reader, options); + break; + case "map_with_undeclared_properties_anytype_3": + mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_with_undeclared_properties_string": + mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref reader, options); + break; + case "anytype_1": + anytype1 = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, options); + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, options); + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, options); + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, options); + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, options); + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs index 4d287b1d2fd..122d4658dd4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Animal /// - public partial class Animal : IEquatable, IValidatableObject + public partial class Animal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// color (default to "red") + [JsonConstructor] public Animal(string className, string color = "red") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for Animal and cannot be null."); + if (color == null) + throw new ArgumentNullException("color is a required property for Animal and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Color = color; } @@ -59,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 Animal).AreEqual; - } - - /// - /// Returns true if Animal instances are equal - /// - /// Instance of Animal to be compared - /// Boolean - public bool Equals(Animal 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +105,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Animal + /// + public class AnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + string color = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "color": + color = reader.GetString(); + break; + default: + break; + } + } + } + + return new Animal(className, color); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", animal.ClassName); + writer.WriteString("color", animal.Color); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs index 9410088a413..fba4da09247 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,19 +26,35 @@ namespace Org.OpenAPITools.Model /// /// ApiResponse /// - public partial class ApiResponse : IEquatable, IValidatableObject + public partial class ApiResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// /// code - /// type /// message - public ApiResponse(int code = default, string type = default, string message = default) + /// type + [JsonConstructor] + public ApiResponse(int code, string message, string type) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (code == null) + throw new ArgumentNullException("code is a required property for ApiResponse and cannot be null."); + + if (type == null) + throw new ArgumentNullException("type is a required property for ApiResponse and cannot be null."); + + if (message == null) + throw new ArgumentNullException("message is a required property for ApiResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Code = code; - Type = type; Message = message; + Type = type; } /// @@ -48,23 +63,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("code")] public int Code { get; set; } - /// - /// Gets or Sets Type - /// - [JsonPropertyName("type")] - public string Type { 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,59 +90,12 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); - sb.Append(" Type: ").Append(Type).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ApiResponse).AreEqual; - } - - /// - /// Returns true if ApiResponse instances are equal - /// - /// Instance of ApiResponse to be compared - /// Boolean - public bool Equals(ApiResponse 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) + this.Code.GetHashCode(); - if (this.Type != null) - { - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - } - if (this.Message != null) - { - hashCode = (hashCode * 59) + this.Message.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ApiResponse + /// + public class ApiResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ApiResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int code = default; + string message = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "code": + code = reader.GetInt32(); + break; + case "message": + message = reader.GetString(); + break; + case "type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new ApiResponse(code, message, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("code", (int)apiResponse.Code); + writer.WriteString("message", apiResponse.Message); + writer.WriteString("type", apiResponse.Type); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs index d6a9cf50290..2d5443fbd52 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Apple /// - public partial class Apple : IEquatable, IValidatableObject + public partial class Apple : IValidatableObject { /// /// Initializes a new instance of the class. /// /// cultivar /// origin - public Apple(string cultivar = default, string origin = default) + [JsonConstructor] + public Apple(string cultivar, string origin) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (cultivar == null) + throw new ArgumentNullException("cultivar is a required property for Apple and cannot be null."); + + if (origin == null) + throw new ArgumentNullException("origin is a required property for Apple and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Origin = origin; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 Apple).AreEqual; - } - - /// - /// Returns true if Apple instances are equal - /// - /// Instance of Apple to be compared - /// Boolean - public bool Equals(Apple 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - if (this.Origin != null) - { - hashCode = (hashCode * 59) + this.Origin.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -143,4 +109,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Apple + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + string origin = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "origin": + origin = reader.GetString(); + break; + default: + break; + } + } + } + + return new Apple(cultivar, origin); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", apple.Cultivar); + writer.WriteString("origin", apple.Origin); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs index 48e37cc0aa8..bae73be3242 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// AppleReq /// - public partial class AppleReq : IEquatable, IValidatableObject + public partial class AppleReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// cultivar (required) + /// cultivar /// mealy - public AppleReq(string cultivar, bool mealy = default) + [JsonConstructor] + public AppleReq(string cultivar, bool mealy) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (cultivar == null) throw new ArgumentNullException("cultivar is a required property for AppleReq and cannot be null."); + if (mealy == null) + throw new ArgumentNullException("mealy is a required property for AppleReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Cultivar = cultivar; Mealy = mealy; } @@ -68,45 +77,6 @@ namespace Org.OpenAPITools.Model 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 AppleReq).AreEqual; - } - - /// - /// Returns true if AppleReq instances are equal - /// - /// Instance of AppleReq to be compared - /// Boolean - public bool Equals(AppleReq 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; - if (this.Cultivar != null) - { - hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,4 +88,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type AppleReq + /// + public class AppleReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AppleReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string cultivar = default; + bool mealy = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "cultivar": + cultivar = reader.GetString(); + break; + case "mealy": + mealy = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new AppleReq(cultivar, mealy); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("cultivar", appleReq.Cultivar); + writer.WriteBoolean("mealy", appleReq.Mealy); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 256a6b596ad..ea6a1f3caba 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfArrayOfNumberOnly /// - public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayArrayNumber - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber = default) + [JsonConstructor] + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayArrayNumber == null) + throw new ArgumentNullException("arrayArrayNumber is a required property for ArrayOfArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayNumber = arrayArrayNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfArrayOfNumberOnly 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; - if (this.ArrayArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfArrayOfNumberOnly + /// + public class ArrayOfArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayArrayNumber": + arrayArrayNumber = JsonSerializer.Deserialize>>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 6c462dddf1e..c09645642c6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ArrayOfNumberOnly /// - public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + public partial class ArrayOfNumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// arrayNumber - public ArrayOfNumberOnly(List arrayNumber = default) + [JsonConstructor] + public ArrayOfNumberOnly(List arrayNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayNumber == null) + throw new ArgumentNullException("arrayNumber is a required property for ArrayOfNumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayNumber = arrayNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ArrayOfNumberOnly).AreEqual; - } - - /// - /// Returns true if ArrayOfNumberOnly instances are equal - /// - /// Instance of ArrayOfNumberOnly to be compared - /// Boolean - public bool Equals(ArrayOfNumberOnly 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; - if (this.ArrayNumber != null) - { - hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayOfNumberOnly + /// + public class ArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayOfNumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ArrayNumber": + arrayNumber = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayOfNumberOnly(arrayNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs index f9872d70105..ef26590ab3c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,37 @@ namespace Org.OpenAPITools.Model /// /// ArrayTest /// - public partial class ArrayTest : IEquatable, IValidatableObject + public partial class ArrayTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayOfString /// arrayArrayOfInteger /// arrayArrayOfModel - public ArrayTest(List arrayOfString = default, List> arrayArrayOfInteger = default, List> arrayArrayOfModel = default) + /// arrayOfString + [JsonConstructor] + public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) { - ArrayOfString = arrayOfString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayOfString == null) + throw new ArgumentNullException("arrayOfString is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfInteger == null) + throw new ArgumentNullException("arrayArrayOfInteger is a required property for ArrayTest and cannot be null."); + + if (arrayArrayOfModel == null) + throw new ArgumentNullException("arrayArrayOfModel is a required property for ArrayTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayArrayOfInteger = arrayArrayOfInteger; ArrayArrayOfModel = arrayArrayOfModel; + ArrayOfString = arrayOfString; } - /// - /// Gets or Sets ArrayOfString - /// - [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } - /// /// Gets or Sets ArrayArrayOfInteger /// @@ -60,11 +69,17 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,63 +89,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); - sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayTest).AreEqual; - } - - /// - /// Returns true if ArrayTest instances are equal - /// - /// Instance of ArrayTest to be compared - /// Boolean - public bool Equals(ArrayTest 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; - if (this.ArrayOfString != null) - { - hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); - } - if (this.ArrayArrayOfInteger != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); - } - if (this.ArrayArrayOfModel != null) - { - hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +107,84 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ArrayTest + /// + public class ArrayTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ArrayTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List> arrayArrayOfInteger = default; + List> arrayArrayOfModel = default; + List arrayOfString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_array_of_integer": + arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_array_of_model": + arrayArrayOfModel = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "array_of_string": + arrayOfString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, options); + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, options); + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs index 3192691eb71..129aec2d593 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Banana /// - public partial class Banana : IEquatable, IValidatableObject + public partial class Banana : IValidatableObject { /// /// Initializes a new instance of the class. /// /// lengthCm - public Banana(decimal lengthCm = default) + [JsonConstructor] + public Banana(decimal lengthCm) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (lengthCm == null) + throw new ArgumentNullException("lengthCm is a required property for Banana and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 Banana).AreEqual; - } - - /// - /// Returns true if Banana instances are equal - /// - /// Instance of Banana to be compared - /// Boolean - public bool Equals(Banana 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) + this.LengthCm.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Banana + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Banana(lengthCm); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)banana.LengthCm); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs index 95ea0488f23..1ef87ba0994 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// BananaReq /// - public partial class BananaReq : IEquatable, IValidatableObject + public partial class BananaReq : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// lengthCm (required) + /// lengthCm /// sweet - public BananaReq(decimal lengthCm, bool sweet = default) + [JsonConstructor] + public BananaReq(decimal lengthCm, bool sweet) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (lengthCm == null) throw new ArgumentNullException("lengthCm is a required property for BananaReq and cannot be null."); + if (sweet == null) + throw new ArgumentNullException("sweet is a required property for BananaReq and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + LengthCm = lengthCm; Sweet = sweet; } @@ -68,42 +77,6 @@ namespace Org.OpenAPITools.Model 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 BananaReq).AreEqual; - } - - /// - /// Returns true if BananaReq instances are equal - /// - /// Instance of BananaReq to be compared - /// Boolean - public bool Equals(BananaReq 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) + this.LengthCm.GetHashCode(); - hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -115,4 +88,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BananaReq + /// + public class BananaReqJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BananaReq Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal lengthCm = default; + bool sweet = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "lengthCm": + lengthCm = reader.GetInt32(); + break; + case "sweet": + sweet = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new BananaReq(lengthCm, sweet); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("lengthCm", (int)bananaReq.LengthCm); + writer.WriteBoolean("sweet", bananaReq.Sweet); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs index fc19bc19279..de3bca6d08c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// BasquePig /// - public partial class BasquePig : IEquatable, IValidatableObject + public partial class BasquePig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public BasquePig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for BasquePig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 BasquePig).AreEqual; - } - - /// - /// Returns true if BasquePig instances are equal - /// - /// Instance of BasquePig to be compared - /// Boolean - public bool Equals(BasquePig 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type BasquePig + /// + public class BasquePigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override BasquePig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new BasquePig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", basquePig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs index 92d92494967..0d25bc70612 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,32 +26,58 @@ namespace Org.OpenAPITools.Model /// /// Capitalization /// - public partial class Capitalization : IEquatable, IValidatableObject + public partial class Capitalization : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// smallCamel + /// Name of the pet /// capitalCamel - /// smallSnake /// capitalSnake /// sCAETHFlowPoints - /// Name of the pet - public Capitalization(string smallCamel = default, string capitalCamel = default, string smallSnake = default, string capitalSnake = default, string sCAETHFlowPoints = default, string aTTNAME = default) + /// smallCamel + /// smallSnake + [JsonConstructor] + public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) { - SmallCamel = smallCamel; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (smallCamel == null) + throw new ArgumentNullException("smallCamel is a required property for Capitalization and cannot be null."); + + if (capitalCamel == null) + throw new ArgumentNullException("capitalCamel is a required property for Capitalization and cannot be null."); + + if (smallSnake == null) + throw new ArgumentNullException("smallSnake is a required property for Capitalization and cannot be null."); + + if (capitalSnake == null) + throw new ArgumentNullException("capitalSnake is a required property for Capitalization and cannot be null."); + + if (sCAETHFlowPoints == null) + throw new ArgumentNullException("sCAETHFlowPoints is a required property for Capitalization and cannot be null."); + + if (aTTNAME == null) + throw new ArgumentNullException("aTTNAME is a required property for Capitalization and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ATT_NAME = aTTNAME; CapitalCamel = capitalCamel; - SmallSnake = smallSnake; CapitalSnake = capitalSnake; SCAETHFlowPoints = sCAETHFlowPoints; - ATT_NAME = aTTNAME; + SmallCamel = smallCamel; + SmallSnake = smallSnake; } /// - /// Gets or Sets SmallCamel + /// Name of the pet /// - [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + /// Name of the pet + [JsonPropertyName("ATT_NAME")] + public string ATT_NAME { get; set; } /// /// Gets or Sets CapitalCamel @@ -60,12 +85,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("CapitalCamel")] public string CapitalCamel { get; set; } - /// - /// Gets or Sets SmallSnake - /// - [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } - /// /// Gets or Sets CapitalSnake /// @@ -79,17 +98,22 @@ namespace Org.OpenAPITools.Model public string SCAETHFlowPoints { get; set; } /// - /// Name of the pet + /// Gets or Sets SmallCamel /// - /// Name of the pet - [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -99,78 +123,16 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); - sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); - sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); - sb.Append(" ATT_NAME: ").Append(ATT_NAME).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Capitalization).AreEqual; - } - - /// - /// Returns true if Capitalization instances are equal - /// - /// Instance of Capitalization to be compared - /// Boolean - public bool Equals(Capitalization 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; - if (this.SmallCamel != null) - { - hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); - } - if (this.CapitalCamel != null) - { - hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); - } - if (this.SmallSnake != null) - { - hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); - } - if (this.CapitalSnake != null) - { - hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); - } - if (this.SCAETHFlowPoints != null) - { - hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); - } - if (this.ATT_NAME != null) - { - hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -182,4 +144,96 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Capitalization + /// + public class CapitalizationJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Capitalization Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string aTTNAME = default; + string capitalCamel = default; + string capitalSnake = default; + string sCAETHFlowPoints = default; + string smallCamel = default; + string smallSnake = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "ATT_NAME": + aTTNAME = reader.GetString(); + break; + case "CapitalCamel": + capitalCamel = reader.GetString(); + break; + case "Capital_Snake": + capitalSnake = reader.GetString(); + break; + case "SCA_ETH_Flow_Points": + sCAETHFlowPoints = reader.GetString(); + break; + case "smallCamel": + smallCamel = reader.GetString(); + break; + case "small_Snake": + smallSnake = reader.GetString(); + break; + default: + break; + } + } + } + + return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + 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); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs index b8c35dd406a..462e1e3d6ed 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,16 +26,17 @@ namespace Org.OpenAPITools.Model /// /// Cat /// - public partial class Cat : Animal, IEquatable + public partial class Cat : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - /// className (required) + /// className /// color (default to "red") - public Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string color = "red") : base(className, color) + [JsonConstructor] + internal Cat(Dictionary dictionary, CatAllOf catAllOf, string className, string color = "red") : base(className, color) { Dictionary = dictionary; CatAllOf = catAllOf; @@ -64,40 +64,6 @@ namespace Org.OpenAPITools.Model 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 Cat).AreEqual; - } - - /// - /// Returns true if Cat instances are equal - /// - /// Instance of Cat to be compared - /// Boolean - public bool Equals(Cat 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -105,13 +71,6 @@ namespace Org.OpenAPITools.Model /// public class CatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Cat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -124,24 +83,29 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader dictionaryReader = reader; - bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref dictionaryReader, options, out Dictionary dictionary); + bool dictionaryDeserialized = Client.ClientUtils.TryDeserialize>(ref reader, options, out Dictionary dictionary); Utf8JsonReader catAllOfReader = reader; - bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref catAllOfReader, options, out CatAllOf catAllOf); + bool catAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out CatAllOf catAllOf); string className = default; string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -154,6 +118,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -168,6 +134,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", cat.ClassName); + writer.WriteString("color", cat.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/CatAllOf.cs index f1f19c6c88d..bdda4289814 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// CatAllOf /// - public partial class CatAllOf : IEquatable, IValidatableObject + public partial class CatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// declawed - public CatAllOf(bool declawed = default) + [JsonConstructor] + public CatAllOf(bool declawed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (declawed == null) + throw new ArgumentNullException("declawed is a required property for CatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Declawed = declawed; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 CatAllOf).AreEqual; - } - - /// - /// Returns true if CatAllOf instances are equal - /// - /// Instance of CatAllOf to be compared - /// Boolean - public bool Equals(CatAllOf 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) + this.Declawed.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type CatAllOf + /// + public class CatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override CatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool declawed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "declawed": + declawed = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new CatAllOf(declawed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CatAllOf catAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("declawed", catAllOf.Declawed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs index be6a1620b10..0a34203a8a4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,31 @@ namespace Org.OpenAPITools.Model /// /// Category /// - public partial class Category : IEquatable, IValidatableObject + public partial class Category : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) (default to "default-name") /// id - public Category(string name = "default-name", long id = default) + /// name (default to "default-name") + [JsonConstructor] + public Category(long id, string name = "default-name") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Category and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Category and cannot be null."); - Name = name; - Id = id; - } +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - /// - /// Gets or Sets Name - /// - [JsonPropertyName("name")] - public string Name { get; set; } + Id = id; + Name = name; + } /// /// Gets or Sets Id @@ -55,11 +58,17 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -69,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); - sb.Append(" Name: ").Append(Name).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Category).AreEqual; - } - - /// - /// Returns true if Category instances are equal - /// - /// Instance of Category to be compared - /// Boolean - public bool Equals(Category 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Category + /// + public class CategoryJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Category Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Category(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Category category, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)category.Id); + writer.WriteString("name", category.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs index 5245528adb8..eac43e23273 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ChildCat /// - public partial class ChildCat : ParentPet, IEquatable + public partial class ChildCat : ParentPet, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// petType (required) - public ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) + /// petType + [JsonConstructor] + internal ChildCat(ChildCatAllOf childCatAllOf, string petType) : base(petType) { ChildCatAllOf = childCatAllOf; } @@ -56,40 +56,6 @@ namespace Org.OpenAPITools.Model 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 ChildCat).AreEqual; - } - - /// - /// Returns true if ChildCat instances are equal - /// - /// Instance of ChildCat to be compared - /// Boolean - public bool Equals(ChildCat 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -97,13 +63,6 @@ namespace Org.OpenAPITools.Model /// public class ChildCatJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ChildCat).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -116,20 +75,25 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader childCatAllOfReader = reader; - bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref childCatAllOfReader, options, out ChildCatAllOf childCatAllOf); + bool childCatAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ChildCatAllOf childCatAllOf); string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -139,6 +103,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -153,6 +119,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", childCat.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index bc601c217ba..6b768fcd1e7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// ChildCatAllOf /// - public partial class ChildCatAllOf : IEquatable, IValidatableObject + public partial class ChildCatAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name /// petType (default to PetTypeEnum.ChildCat) - public ChildCatAllOf(string name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) + [JsonConstructor] + public ChildCatAllOf(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for ChildCatAllOf and cannot be null."); + + if (petType == null) + throw new ArgumentNullException("petType is a required property for ChildCatAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; PetType = petType; } @@ -48,11 +60,37 @@ namespace Org.OpenAPITools.Model /// /// Enum ChildCat for value: ChildCat /// - [EnumMember(Value = "ChildCat")] ChildCat = 1 } + /// + /// Returns a PetTypeEnum + /// + /// + /// + public static PetTypeEnum PetTypeEnumFromString(string value) + { + if (value == "ChildCat") + return PetTypeEnum.ChildCat; + + throw new NotImplementedException($"Could not convert value to type PetTypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -69,7 +107,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -85,49 +123,6 @@ namespace Org.OpenAPITools.Model 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 ChildCatAllOf).AreEqual; - } - - /// - /// Returns true if ChildCatAllOf instances are equal - /// - /// Instance of ChildCatAllOf to be compared - /// Boolean - public bool Equals(ChildCatAllOf 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +134,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ChildCatAllOf + /// + public class ChildCatAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ChildCatAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + ChildCatAllOf.PetTypeEnum petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + case "pet_type": + string petTypeRawValue = reader.GetString(); + petType = ChildCatAllOf.PetTypeEnumFromString(petTypeRawValue); + break; + default: + break; + } + } + } + + return new ChildCatAllOf(name, petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChildCatAllOf childCatAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", childCatAllOf.Name); + var petTypeRawValue = ChildCatAllOf.PetTypeEnumToJsonValue(childCatAllOf.PetType); + if (petTypeRawValue != null) + writer.WriteString("pet_type", petTypeRawValue); + else + writer.WriteNull("pet_type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs index 84a40d94899..be70d0da28b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model with \"_class\" property /// - public partial class ClassModel : IEquatable, IValidatableObject + public partial class ClassModel : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _class - public ClassModel(string _class = default) + /// classProperty + [JsonConstructor] + public ClassModel(string classProperty) { - Class = _class; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for ClassModel and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; } /// - /// Gets or Sets Class + /// Gets or Sets ClassProperty /// [JsonPropertyName("_class")] - public string Class { get; set; } + public string ClassProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); - sb.Append(" Class: ").Append(Class).Append("\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).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 ClassModel).AreEqual; - } - - /// - /// Returns true if ClassModel instances are equal - /// - /// Instance of ClassModel to be compared - /// Boolean - public bool Equals(ClassModel 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; - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ClassModel + /// + public class ClassModelJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ClassModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_class": + classProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ClassModel(classProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_class", classModel.ClassProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 2ec6fa15f31..b4c3977c995 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ComplexQuadrilateral /// - public partial class ComplexQuadrilateral : IEquatable, IValidatableObject + public partial class ComplexQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal ComplexQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 ComplexQuadrilateral).AreEqual; - } - - /// - /// Returns true if ComplexQuadrilateral instances are equal - /// - /// Instance of ComplexQuadrilateral to be compared - /// Boolean - public bool Equals(ComplexQuadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class ComplexQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ComplexQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs index fdcd66cce71..f0d02bc0b01 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DanishPig /// - public partial class DanishPig : IEquatable, IValidatableObject + public partial class DanishPig : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className + [JsonConstructor] public DanishPig(string className) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (className == null) throw new ArgumentNullException("className is a required property for DanishPig and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DanishPig).AreEqual; - } - - /// - /// Returns true if DanishPig instances are equal - /// - /// Instance of DanishPig to be compared - /// Boolean - public bool Equals(DanishPig 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DanishPig + /// + public class DanishPigJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DanishPig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + default: + break; + } + } + } + + return new DanishPig(className); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", danishPig.ClassName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs index d04aa006550..c5e0f5e2ca4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DeprecatedObject /// - public partial class DeprecatedObject : IEquatable, IValidatableObject + public partial class DeprecatedObject : IValidatableObject { /// /// Initializes a new instance of the class. /// /// name - public DeprecatedObject(string name = default) + [JsonConstructor] + public DeprecatedObject(string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for DeprecatedObject and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Name = name; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DeprecatedObject).AreEqual; - } - - /// - /// Returns true if DeprecatedObject instances are equal - /// - /// Instance of DeprecatedObject to be compared - /// Boolean - public bool Equals(DeprecatedObject 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DeprecatedObject + /// + public class DeprecatedObjectJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DeprecatedObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new DeprecatedObject(name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("name", deprecatedObject.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs index e00bc00421c..ad3da1cfd7d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,16 @@ namespace Org.OpenAPITools.Model /// /// Dog /// - public partial class Dog : Animal, IEquatable + public partial class Dog : Animal, IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// className (required) + /// className /// color (default to "red") - public Dog(DogAllOf dogAllOf, string className, string color = "red") : base(className, color) + [JsonConstructor] + internal Dog(DogAllOf dogAllOf, string className, string color = "red") : base(className, color) { DogAllOf = dogAllOf; } @@ -57,40 +57,6 @@ namespace Org.OpenAPITools.Model 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 Dog).AreEqual; - } - - /// - /// Returns true if Dog instances are equal - /// - /// Instance of Dog to be compared - /// Boolean - public bool Equals(Dog 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -98,13 +64,6 @@ namespace Org.OpenAPITools.Model /// public class DogJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Dog).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -117,21 +76,26 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader dogAllOfReader = reader; - bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref dogAllOfReader, options, out DogAllOf dogAllOf); + bool dogAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out DogAllOf dogAllOf); string className = default; string color = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -144,6 +108,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -158,6 +124,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", dog.ClassName); + writer.WriteString("color", dog.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DogAllOf.cs index e35252fa263..2e3092d06b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// DogAllOf /// - public partial class DogAllOf : IEquatable, IValidatableObject + public partial class DogAllOf : IValidatableObject { /// /// Initializes a new instance of the class. /// /// breed - public DogAllOf(string breed = default) + [JsonConstructor] + public DogAllOf(string breed) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (breed == null) + throw new ArgumentNullException("breed is a required property for DogAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Breed = breed; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 DogAllOf).AreEqual; - } - - /// - /// Returns true if DogAllOf instances are equal - /// - /// Instance of DogAllOf to be compared - /// Boolean - public bool Equals(DogAllOf 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; - if (this.Breed != null) - { - hashCode = (hashCode * 59) + this.Breed.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type DogAllOf + /// + public class DogAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override DogAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string breed = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "breed": + breed = reader.GetString(); + break; + default: + break; + } + } + } + + return new DogAllOf(breed); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DogAllOf dogAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("breed", dogAllOf.Breed); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs index 4cb653c55d2..6de00f19504 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,37 @@ namespace Org.OpenAPITools.Model /// /// Drawing /// - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape /// shapeOrNull - /// nullableShape /// shapes - public Drawing(Shape mainShape = default, ShapeOrNull shapeOrNull = default, NullableShape nullableShape = default, List shapes = default) : base() + /// nullableShape + [JsonConstructor] + public Drawing(Shape mainShape, ShapeOrNull shapeOrNull, List shapes, NullableShape nullableShape = default) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mainShape == null) + throw new ArgumentNullException("mainShape is a required property for Drawing and cannot be null."); + + if (shapeOrNull == null) + throw new ArgumentNullException("shapeOrNull is a required property for Drawing and cannot be null."); + + if (shapes == null) + throw new ArgumentNullException("shapes is a required property for Drawing and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + MainShape = mainShape; ShapeOrNull = shapeOrNull; - NullableShape = nullableShape; Shapes = shapes; + NullableShape = nullableShape; } /// @@ -56,18 +71,18 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("shapeOrNull")] public ShapeOrNull ShapeOrNull { get; set; } - /// - /// Gets or Sets NullableShape - /// - [JsonPropertyName("nullableShape")] - public NullableShape NullableShape { get; set; } - /// /// Gets or Sets Shapes /// [JsonPropertyName("shapes")] public List Shapes { get; set; } + /// + /// Gets or Sets NullableShape + /// + [JsonPropertyName("nullableShape")] + public NullableShape NullableShape { get; set; } + /// /// Returns the string presentation of the object /// @@ -79,61 +94,11 @@ namespace Org.OpenAPITools.Model sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); - sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" NullableShape: ").Append(NullableShape).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 Drawing).AreEqual; - } - - /// - /// Returns true if Drawing instances are equal - /// - /// Instance of Drawing to be compared - /// Boolean - public bool Equals(Drawing 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 = base.GetHashCode(); - if (this.MainShape != null) - { - hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); - } - if (this.ShapeOrNull != null) - { - hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); - } - if (this.NullableShape != null) - { - hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); - } - if (this.Shapes != null) - { - hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -145,4 +110,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Drawing + /// + public class DrawingJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Drawing Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Shape mainShape = default; + ShapeOrNull shapeOrNull = default; + List shapes = default; + NullableShape nullableShape = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "mainShape": + mainShape = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapeOrNull": + shapeOrNull = JsonSerializer.Deserialize(ref reader, options); + break; + case "shapes": + shapes = JsonSerializer.Deserialize>(ref reader, options); + break; + case "nullableShape": + nullableShape = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new Drawing(mainShape, shapeOrNull, shapes, nullableShape); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, options); + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, options); + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, options); + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 92f07ad2ee5..c6dcd8b5b24 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,80 @@ namespace Org.OpenAPITools.Model /// /// EnumArrays /// - public partial class EnumArrays : IEquatable, IValidatableObject + public partial class EnumArrays : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) + /// justSymbol + [JsonConstructor] + public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) { - JustSymbol = justSymbol; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justSymbol == null) + throw new ArgumentNullException("justSymbol is a required property for EnumArrays and cannot be null."); + + if (arrayEnum == null) + throw new ArgumentNullException("arrayEnum is a required property for EnumArrays and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ArrayEnum = arrayEnum; + JustSymbol = justSymbol; + } + + /// + /// Defines ArrayEnum + /// + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + Crab = 2 + + } + + /// + /// Returns a ArrayEnumEnum + /// + /// + /// + public static ArrayEnumEnum ArrayEnumEnumFromString(string value) + { + if (value == "fish") + return ArrayEnumEnum.Fish; + + if (value == "crab") + return ArrayEnumEnum.Crab; + + throw new NotImplementedException($"Could not convert value to type ArrayEnumEnum: '{value}'"); + } + + /// + /// Returns equivalent 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}'"); } /// @@ -48,42 +110,54 @@ namespace Org.OpenAPITools.Model /// /// Enum GreaterThanOrEqualTo for value: >= /// - [EnumMember(Value = ">=")] GreaterThanOrEqualTo = 1, /// /// Enum Dollar for value: $ /// - [EnumMember(Value = "$")] Dollar = 2 } + /// + /// Returns a JustSymbolEnum + /// + /// + /// + public static JustSymbolEnum JustSymbolEnumFromString(string value) + { + if (value == ">=") + return JustSymbolEnum.GreaterThanOrEqualTo; + + if (value == "$") + return JustSymbolEnum.Dollar; + + throw new NotImplementedException($"Could not convert value to type JustSymbolEnum: '{value}'"); + } + + /// + /// Returns equivalent 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; } - /// - /// Defines ArrayEnum - /// - public enum ArrayEnumEnum - { - /// - /// Enum Fish for value: fish - /// - [EnumMember(Value = "fish")] - Fish = 1, - - /// - /// Enum Crab for value: crab - /// - [EnumMember(Value = "crab")] - Crab = 2 - - } - /// /// Gets or Sets ArrayEnum /// @@ -94,7 +168,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -104,55 +178,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); - sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumArrays).AreEqual; - } - - /// - /// Returns true if EnumArrays instances are equal - /// - /// Instance of EnumArrays to be compared - /// Boolean - public bool Equals(EnumArrays 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) + this.JustSymbol.GetHashCode(); - if (this.ArrayEnum != null) - { - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -164,4 +195,82 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumArrays + /// + public class EnumArraysJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumArrays Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List arrayEnum = default; + EnumArrays.JustSymbolEnum justSymbol = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_enum": + arrayEnum = JsonSerializer.Deserialize>(ref reader, options); + break; + case "just_symbol": + string justSymbolRawValue = reader.GetString(); + justSymbol = EnumArrays.JustSymbolEnumFromString(justSymbolRawValue); + break; + default: + break; + } + } + } + + return new EnumArrays(arrayEnum, justSymbol); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, options); + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); + if (justSymbolRawValue != null) + writer.WriteString("just_symbol", justSymbolRawValue); + else + writer.WriteNull("just_symbol"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs index 390f7f6ea5c..ac9fc84aad6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Abc for value: _abc /// - [EnumMember(Value = "_abc")] Abc = 1, /// /// Enum Efg for value: -efg /// - [EnumMember(Value = "-efg")] Efg = 2, /// /// Enum Xyz for value: (xyz) /// - [EnumMember(Value = "(xyz)")] Xyz = 3 } + + public class EnumClassConverter : JsonConverter + { + public static EnumClass FromString(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + throw new NotImplementedException($"Could not convert value to type EnumClass: '{value}'"); + } + + public static EnumClass? FromStringOrDefault(string value) + { + if (value == "_abc") + return EnumClass.Abc; + + if (value == "-efg") + return EnumClass.Efg; + + if (value == "(xyz)") + return EnumClass.Xyz; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override EnumClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + EnumClass? result = EnumClassConverter.FromString(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()); + } + } + + public class EnumClassNullableConverter : JsonConverter + { + /// + /// Returns a EnumClass from the Json object + /// + /// + /// + /// + /// + public override EnumClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + EnumClass? result = EnumClassConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs index 273116bc036..42b07a14075 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,98 +26,64 @@ namespace Org.OpenAPITools.Model /// /// EnumTest /// - public partial class EnumTest : IEquatable, IValidatableObject + public partial class EnumTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// enumStringRequired (required) - /// enumString /// enumInteger /// enumIntegerOnly /// enumNumber - /// outerEnum - /// outerEnumInteger + /// enumString + /// enumStringRequired /// outerEnumDefaultValue + /// outerEnumInteger /// outerEnumIntegerDefaultValue - public EnumTest(EnumStringRequiredEnum enumStringRequired, EnumStringEnum enumString = default, EnumIntegerEnum enumInteger = default, EnumIntegerOnlyEnum enumIntegerOnly = default, EnumNumberEnum enumNumber = default, OuterEnum outerEnum = default, OuterEnumInteger outerEnumInteger = default, OuterEnumDefaultValue outerEnumDefaultValue = default, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = default) + /// outerEnum + [JsonConstructor] + public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (enumString == null) + throw new ArgumentNullException("enumString is a required property for EnumTest and cannot be null."); + if (enumStringRequired == null) throw new ArgumentNullException("enumStringRequired is a required property for EnumTest and cannot be null."); - EnumStringRequired = enumStringRequired; - EnumString = enumString; + if (enumInteger == null) + throw new ArgumentNullException("enumInteger is a required property for EnumTest and cannot be null."); + + if (enumIntegerOnly == null) + throw new ArgumentNullException("enumIntegerOnly is a required property for EnumTest and cannot be null."); + + if (enumNumber == null) + throw new ArgumentNullException("enumNumber is a required property for EnumTest and cannot be null."); + + if (outerEnumInteger == null) + throw new ArgumentNullException("outerEnumInteger is a required property for EnumTest and cannot be null."); + + if (outerEnumDefaultValue == null) + throw new ArgumentNullException("outerEnumDefaultValue is a required property for EnumTest and cannot be null."); + + if (outerEnumIntegerDefaultValue == null) + throw new ArgumentNullException("outerEnumIntegerDefaultValue is a required property for EnumTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + EnumInteger = enumInteger; EnumIntegerOnly = enumIntegerOnly; EnumNumber = enumNumber; - OuterEnum = outerEnum; - OuterEnumInteger = outerEnumInteger; + EnumString = enumString; + EnumStringRequired = enumStringRequired; OuterEnumDefaultValue = outerEnumDefaultValue; + OuterEnumInteger = outerEnumInteger; OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + OuterEnum = outerEnum; } - /// - /// Defines EnumStringRequired - /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumStringRequired - /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } - - /// - /// Defines EnumString - /// - public enum EnumStringEnum - { - /// - /// Enum UPPER for value: UPPER - /// - [EnumMember(Value = "UPPER")] - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - [EnumMember(Value = "lower")] - Lower = 2, - - /// - /// Enum Empty for value: - /// - [EnumMember(Value = "")] - Empty = 3 - - } - - /// - /// Gets or Sets EnumString - /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } - /// /// Defines EnumInteger /// @@ -136,6 +101,33 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerEnum + /// + /// + /// + public static EnumIntegerEnum EnumIntegerEnumFromString(string value) + { + if (value == (1).ToString()) + return EnumIntegerEnum.NUMBER_1; + + if (value == (-1).ToString()) + return EnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumInteger /// @@ -159,6 +151,33 @@ namespace Org.OpenAPITools.Model } + /// + /// Returns a EnumIntegerOnlyEnum + /// + /// + /// + public static EnumIntegerOnlyEnum EnumIntegerOnlyEnumFromString(string value) + { + if (value == (2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_2; + + if (value == (-2).ToString()) + return EnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) + { + return (int) value; + } + /// /// Gets or Sets EnumIntegerOnly /// @@ -173,17 +192,48 @@ namespace Org.OpenAPITools.Model /// /// Enum NUMBER_1_DOT_1 for value: 1.1 /// - [EnumMember(Value = "1.1")] NUMBER_1_DOT_1 = 1, /// /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 /// - [EnumMember(Value = "-1.2")] NUMBER_MINUS_1_DOT_2 = 2 } + /// + /// Returns a EnumNumberEnum + /// + /// + /// + public static EnumNumberEnum EnumNumberEnumFromString(string value) + { + if (value == "1.1") + return EnumNumberEnum.NUMBER_1_DOT_1; + + if (value == "-1.2") + return EnumNumberEnum.NUMBER_MINUS_1_DOT_2; + + throw new NotImplementedException($"Could not convert value to type EnumNumberEnum: '{value}'"); + } + + /// + /// Returns equivalent json value + /// + /// + /// + /// + public static string 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 /// @@ -191,16 +241,138 @@ namespace Org.OpenAPITools.Model public EnumNumberEnum EnumNumber { get; set; } /// - /// Gets or Sets OuterEnum + /// Defines EnumString /// - [JsonPropertyName("outerEnum")] - public OuterEnum OuterEnum { get; set; } + public enum EnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3 + + } /// - /// Gets or Sets OuterEnumInteger + /// Returns a EnumStringEnum /// - [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + /// + /// + public static EnumStringEnum EnumStringEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringEnum.UPPER; + + if (value == "lower") + return EnumStringEnum.Lower; + + if (value == "") + return EnumStringEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 + + } + + /// + /// Returns a EnumStringRequiredEnum + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value == "UPPER") + return EnumStringRequiredEnum.UPPER; + + if (value == "lower") + return EnumStringRequiredEnum.Lower; + + if (value == "") + return EnumStringRequiredEnum.Empty; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 ""; + + 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 @@ -208,17 +380,29 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -228,66 +412,19 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); - sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); - sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumTest).AreEqual; - } - - /// - /// Returns true if EnumTest instances are equal - /// - /// Instance of EnumTest to be compared - /// Boolean - public bool Equals(EnumTest 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) + this.EnumStringRequired.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); - hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -299,4 +436,143 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type EnumTest + /// + public class EnumTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override EnumTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "enum_integer": + enumInteger = (EnumTest.EnumIntegerEnum) reader.GetInt32(); + break; + case "enum_integer_only": + enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum) reader.GetInt32(); + break; + case "enum_number": + enumNumber = (EnumTest.EnumNumberEnum) reader.GetInt32(); + break; + case "enum_string": + string enumStringRawValue = reader.GetString(); + enumString = EnumTest.EnumStringEnumFromString(enumStringRawValue); + break; + case "enum_string_required": + string enumStringRequiredRawValue = reader.GetString(); + enumStringRequired = EnumTest.EnumStringRequiredEnumFromString(enumStringRequiredRawValue); + break; + case "outerEnumDefaultValue": + string outerEnumDefaultValueRawValue = reader.GetString(); + outerEnumDefaultValue = OuterEnumDefaultValueConverter.FromString(outerEnumDefaultValueRawValue); + break; + case "outerEnumInteger": + string outerEnumIntegerRawValue = reader.GetString(); + outerEnumInteger = OuterEnumIntegerConverter.FromString(outerEnumIntegerRawValue); + break; + case "outerEnumIntegerDefaultValue": + string outerEnumIntegerDefaultValueRawValue = reader.GetString(); + outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValueConverter.FromString(outerEnumIntegerDefaultValueRawValue); + break; + case "outerEnum": + string outerEnumRawValue = reader.GetString(); + outerEnum = OuterEnumConverter.FromStringOrDefault(outerEnumRawValue); + break; + default: + break; + } + } + } + + return new EnumTest(enumInteger, enumIntegerOnly, enumNumber, enumString, enumStringRequired, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue, outerEnum); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("enum_integer", (int)enumTest.EnumInteger); + writer.WriteNumber("enum_integer_only", (int)enumTest.EnumIntegerOnly); + writer.WriteNumber("enum_number", (int)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 = OuterEnumDefaultValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (outerEnumDefaultValueRawValue != null) + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + else + writer.WriteNull("outerEnumDefaultValue"); + var outerEnumIntegerRawValue = OuterEnumIntegerConverter.ToJsonValue(enumTest.OuterEnumInteger); + if (outerEnumIntegerRawValue != null) + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + else + writer.WriteNull("outerEnumInteger"); + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); + if (outerEnumIntegerDefaultValueRawValue != null) + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + else + writer.WriteNull("outerEnumIntegerDefaultValue"); + if (enumTest.OuterEnum == null) + writer.WriteNull("outerEnum"); + var outerEnumRawValue = OuterEnumConverter.ToJsonValue(enumTest.OuterEnum.Value); + if (outerEnumRawValue != null) + writer.WriteString("outerEnum", outerEnumRawValue); + else + writer.WriteNull("outerEnum"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index e6fc1aa4f31..c4d54d076a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// EquilateralTriangle /// - public partial class EquilateralTriangle : IEquatable, IValidatableObject + public partial class EquilateralTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal EquilateralTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 EquilateralTriangle).AreEqual; - } - - /// - /// Returns true if EquilateralTriangle instances are equal - /// - /// Instance of EquilateralTriangle to be compared - /// Boolean - public bool Equals(EquilateralTriangle 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class EquilateralTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(EquilateralTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs index 86163355eaf..5762b5a5288 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Must be named `File` for test. /// - public partial class File : IEquatable, IValidatableObject + public partial class File : IValidatableObject { /// /// Initializes a new instance of the class. /// /// Test capitalization - public File(string sourceURI = default) + [JsonConstructor] + public File(string sourceURI) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (sourceURI == null) + throw new ArgumentNullException("sourceURI is a required property for File and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + SourceURI = sourceURI; } @@ -49,7 +58,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -64,48 +73,6 @@ namespace Org.OpenAPITools.Model 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 File).AreEqual; - } - - /// - /// Returns true if File instances are equal - /// - /// Instance of File to be compared - /// Boolean - public bool Equals(File 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; - if (this.SourceURI != null) - { - hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -117,4 +84,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type File + /// + public class FileJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override File Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string sourceURI = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "sourceURI": + sourceURI = reader.GetString(); + break; + default: + break; + } + } + } + + return new File(sourceURI); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("sourceURI", file.SourceURI); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 366ead31ee1..d71951f5df6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// FileSchemaTestClass /// - public partial class FileSchemaTestClass : IEquatable, IValidatableObject + public partial class FileSchemaTestClass : IValidatableObject { /// /// Initializes a new instance of the class. /// /// file /// files - public FileSchemaTestClass(File file = default, List files = default) + [JsonConstructor] + public FileSchemaTestClass(File file, List files) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (file == null) + throw new ArgumentNullException("file is a required property for FileSchemaTestClass and cannot be null."); + + if (files == null) + throw new ArgumentNullException("files is a required property for FileSchemaTestClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + File = file; Files = files; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,52 +84,6 @@ namespace Org.OpenAPITools.Model 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 FileSchemaTestClass).AreEqual; - } - - /// - /// Returns true if FileSchemaTestClass instances are equal - /// - /// Instance of FileSchemaTestClass to be compared - /// Boolean - public bool Equals(FileSchemaTestClass 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; - if (this.File != null) - { - hashCode = (hashCode * 59) + this.File.GetHashCode(); - } - if (this.Files != null) - { - hashCode = (hashCode * 59) + this.Files.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +95,78 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FileSchemaTestClass + /// + public class FileSchemaTestClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FileSchemaTestClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + File file = default; + List files = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "file": + file = JsonSerializer.Deserialize(ref reader, options); + break; + case "files": + files = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new FileSchemaTestClass(file, files); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, options); + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs index 8be5cfe140b..57810a84fef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Foo /// - public partial class Foo : IEquatable, IValidatableObject + public partial class Foo : IValidatableObject { /// /// Initializes a new instance of the class. /// /// bar (default to "bar") + [JsonConstructor] public Foo(string bar = "bar") { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for Foo and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 Foo).AreEqual; - } - - /// - /// Returns true if Foo instances are equal - /// - /// Instance of Foo to be compared - /// Boolean - public bool Equals(Foo 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; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Foo + /// + public class FooJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Foo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + default: + break; + } + } + } + + return new Foo(bar); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", foo.Bar); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index e32cb9257e5..a17a59ac541 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// FooGetDefaultResponse /// - public partial class FooGetDefaultResponse : IEquatable, IValidatableObject + public partial class FooGetDefaultResponse : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _string - public FooGetDefaultResponse(Foo _string = default) + /// stringProperty + [JsonConstructor] + public FooGetDefaultResponse(Foo stringProperty) { - String = _string; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FooGetDefaultResponse and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + StringProperty = stringProperty; } /// - /// Gets or Sets String + /// Gets or Sets StringProperty /// [JsonPropertyName("string")] - public Foo String { get; set; } + public Foo StringProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FooGetDefaultResponse {\n"); - sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).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 FooGetDefaultResponse).AreEqual; - } - - /// - /// Returns true if FooGetDefaultResponse instances are equal - /// - /// Instance of FooGetDefaultResponse to be compared - /// Boolean - public bool Equals(FooGetDefaultResponse 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; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,72 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type FooGetDefaultResponse + /// + public class FooGetDefaultResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FooGetDefaultResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Foo stringProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "string": + stringProperty = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new FooGetDefaultResponse(stringProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.StringProperty, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs index a767556f460..f3b4b2a9946 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,70 +26,113 @@ namespace Org.OpenAPITools.Model /// /// FormatTest /// - public partial class FormatTest : IEquatable, IValidatableObject + public partial class FormatTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// number (required) - /// _byte (required) - /// date (required) - /// password (required) - /// integer + /// binary + /// byteProperty + /// date + /// dateTime + /// decimalProperty + /// doubleProperty + /// floatProperty /// int32 /// int64 - /// _float - /// _double - /// _decimal - /// _string - /// binary - /// dateTime - /// uuid + /// integer + /// number + /// password /// 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. - public FormatTest(decimal number, byte[] _byte, DateTime date, string password, int integer = default, int int32 = default, long int64 = default, float _float = default, double _double = default, decimal _decimal = default, string _string = default, System.IO.Stream binary = default, DateTime dateTime = default, Guid uuid = default, string patternWithDigits = default, string patternWithDigitsAndDelimiter = default) + /// stringProperty + /// uuid + [JsonConstructor] + public FormatTest(System.IO.Stream binary, byte[] byteProperty, DateTime date, DateTime dateTime, decimal decimalProperty, double doubleProperty, float floatProperty, int int32, long int64, int integer, decimal number, string password, string patternWithDigits, string patternWithDigitsAndDelimiter, string stringProperty, Guid uuid) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (integer == null) + throw new ArgumentNullException("integer is a required property for FormatTest and cannot be null."); + + if (int32 == null) + throw new ArgumentNullException("int32 is a required property for FormatTest and cannot be null."); + + if (int64 == null) + throw new ArgumentNullException("int64 is a required property for FormatTest and cannot be null."); + if (number == null) throw new ArgumentNullException("number is a required property for FormatTest and cannot be null."); - if (_byte == null) - throw new ArgumentNullException("_byte is a required property for FormatTest and cannot be null."); + if (floatProperty == null) + throw new ArgumentNullException("floatProperty is a required property for FormatTest and cannot be null."); + + if (doubleProperty == null) + throw new ArgumentNullException("doubleProperty is a required property for FormatTest and cannot be null."); + + if (decimalProperty == null) + throw new ArgumentNullException("decimalProperty is a required property for FormatTest and cannot be null."); + + if (stringProperty == null) + throw new ArgumentNullException("stringProperty is a required property for FormatTest and cannot be null."); + + if (byteProperty == null) + throw new ArgumentNullException("byteProperty is a required property for FormatTest and cannot be null."); + + if (binary == null) + throw new ArgumentNullException("binary is a required property for FormatTest and cannot be null."); if (date == null) throw new ArgumentNullException("date is a required property for FormatTest and cannot be null."); + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for FormatTest and cannot be null."); + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for FormatTest and cannot be null."); + if (password == null) throw new ArgumentNullException("password is a required property for FormatTest and cannot be null."); - Number = number; - Byte = _byte; + if (patternWithDigits == null) + throw new ArgumentNullException("patternWithDigits is a required property for FormatTest and cannot be null."); + + if (patternWithDigitsAndDelimiter == null) + throw new ArgumentNullException("patternWithDigitsAndDelimiter is a required property for FormatTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Binary = binary; + ByteProperty = byteProperty; Date = date; - Password = password; - Integer = integer; + DateTime = dateTime; + DecimalProperty = decimalProperty; + DoubleProperty = doubleProperty; + FloatProperty = floatProperty; Int32 = int32; Int64 = int64; - Float = _float; - Double = _double; - Decimal = _decimal; - String = _string; - Binary = binary; - DateTime = dateTime; - Uuid = uuid; + Integer = integer; + Number = number; + Password = password; PatternWithDigits = patternWithDigits; PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + StringProperty = stringProperty; + Uuid = uuid; } /// - /// Gets or Sets Number + /// Gets or Sets Binary /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get; set; } /// - /// Gets or Sets Byte + /// Gets or Sets ByteProperty /// [JsonPropertyName("byte")] - public byte[] Byte { get; set; } + public byte[] ByteProperty { get; set; } /// /// Gets or Sets Date @@ -99,16 +141,28 @@ namespace Org.OpenAPITools.Model public DateTime Date { get; set; } /// - /// Gets or Sets Password + /// Gets or Sets DateTime /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonPropertyName("dateTime")] + public DateTime DateTime { get; set; } /// - /// Gets or Sets Integer + /// Gets or Sets DecimalProperty /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonPropertyName("decimal")] + public decimal DecimalProperty { get; set; } + + /// + /// Gets or Sets DoubleProperty + /// + [JsonPropertyName("double")] + public double DoubleProperty { get; set; } + + /// + /// Gets or Sets FloatProperty + /// + [JsonPropertyName("float")] + public float FloatProperty { get; set; } /// /// Gets or Sets Int32 @@ -123,46 +177,22 @@ namespace Org.OpenAPITools.Model public long Int64 { get; set; } /// - /// Gets or Sets Float + /// Gets or Sets Integer /// - [JsonPropertyName("float")] - public float Float { get; set; } + [JsonPropertyName("integer")] + public int Integer { get; set; } /// - /// Gets or Sets Double + /// Gets or Sets Number /// - [JsonPropertyName("double")] - public double Double { get; set; } + [JsonPropertyName("number")] + public decimal Number { get; set; } /// - /// Gets or Sets Decimal + /// Gets or Sets Password /// - [JsonPropertyName("decimal")] - public decimal Decimal { get; set; } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public string String { get; set; } - - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - - /// - /// Gets or Sets DateTime - /// - [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } - - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + [JsonPropertyName("password")] + public string Password { get; set; } /// /// A string that is a 10 digit number. Can have leading zeros. @@ -178,11 +208,23 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("pattern_with_digits_and_delimiter")] public string PatternWithDigitsAndDelimiter { get; set; } + /// + /// Gets or Sets StringProperty + /// + [JsonPropertyName("string")] + public string StringProperty { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -192,107 +234,26 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" ByteProperty: ").Append(ByteProperty).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" DecimalProperty: ").Append(DecimalProperty).Append("\n"); + sb.Append(" DoubleProperty: ").Append(DoubleProperty).Append("\n"); + sb.Append(" FloatProperty: ").Append(FloatProperty).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" Decimal: ").Append(Decimal).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Uuid: ").Append(Uuid).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(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); + sb.Append(" StringProperty: ").Append(StringProperty).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 FormatTest).AreEqual; - } - - /// - /// Returns true if FormatTest instances are equal - /// - /// Instance of FormatTest to be compared - /// Boolean - public bool Equals(FormatTest 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) + this.Number.GetHashCode(); - if (this.Byte != null) - { - hashCode = (hashCode * 59) + this.Byte.GetHashCode(); - } - if (this.Date != null) - { - hashCode = (hashCode * 59) + this.Date.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Integer.GetHashCode(); - hashCode = (hashCode * 59) + this.Int32.GetHashCode(); - hashCode = (hashCode * 59) + this.Int64.GetHashCode(); - hashCode = (hashCode * 59) + this.Float.GetHashCode(); - hashCode = (hashCode * 59) + this.Double.GetHashCode(); - hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.Binary != null) - { - hashCode = (hashCode * 59) + this.Binary.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.PatternWithDigits != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); - } - if (this.PatternWithDigitsAndDelimiter != null) - { - hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -300,6 +261,54 @@ namespace Org.OpenAPITools.Model /// Validation Result public IEnumerable Validate(ValidationContext validationContext) { + // DoubleProperty (double) maximum + if (this.DoubleProperty > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value less than or equal to 123.4.", new [] { "DoubleProperty" }); + } + + // DoubleProperty (double) minimum + if (this.DoubleProperty < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DoubleProperty, must be a value greater than or equal to 67.8.", new [] { "DoubleProperty" }); + } + + // FloatProperty (float) maximum + if (this.FloatProperty > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value less than or equal to 987.6.", new [] { "FloatProperty" }); + } + + // FloatProperty (float) minimum + if (this.FloatProperty < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FloatProperty, must be a value greater than or equal to 54.3.", new [] { "FloatProperty" }); + } + + // 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) { @@ -324,61 +333,6 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } - // 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" }); - } - - // 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" }); - } - - // Float (float) maximum - if (this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Float (float) minimum - if (this.Float < (float)54.3) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); - } - - // Double (double) maximum - if (this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if (this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\\d{10}$", RegexOptions.CultureInvariant); if (false == regexPatternWithDigits.Match(this.PatternWithDigits).Success) @@ -393,8 +347,162 @@ namespace Org.OpenAPITools.Model yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } + // StringProperty (string) pattern + Regex regexStringProperty = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexStringProperty.Match(this.StringProperty).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StringProperty, must match a pattern of " + regexStringProperty, new [] { "StringProperty" }); + } + yield break; } } + /// + /// A Json converter for type FormatTest + /// + public class FormatTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override FormatTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + System.IO.Stream binary = default; + byte[] byteProperty = default; + DateTime date = default; + DateTime dateTime = default; + decimal decimalProperty = default; + double doubleProperty = default; + float floatProperty = default; + int int32 = default; + long int64 = default; + int integer = default; + decimal number = default; + string password = default; + string patternWithDigits = default; + string patternWithDigitsAndDelimiter = default; + string stringProperty = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "binary": + binary = JsonSerializer.Deserialize(ref reader, options); + break; + case "byte": + byteProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "date": + date = JsonSerializer.Deserialize(ref reader, options); + break; + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "decimal": + decimalProperty = JsonSerializer.Deserialize(ref reader, options); + break; + case "double": + doubleProperty = reader.GetDouble(); + break; + case "float": + floatProperty = (float)reader.GetDouble(); + break; + case "int32": + int32 = reader.GetInt32(); + break; + case "int64": + int64 = reader.GetInt64(); + break; + case "integer": + integer = reader.GetInt32(); + break; + case "number": + number = reader.GetInt32(); + break; + case "password": + password = reader.GetString(); + break; + case "pattern_with_digits": + patternWithDigits = reader.GetString(); + break; + case "pattern_with_digits_and_delimiter": + patternWithDigitsAndDelimiter = reader.GetString(); + break; + case "string": + stringProperty = reader.GetString(); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new FormatTest(binary, byteProperty, date, dateTime, decimalProperty, doubleProperty, floatProperty, int32, int64, integer, number, password, patternWithDigits, patternWithDigitsAndDelimiter, stringProperty, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, options); + writer.WritePropertyName("byte"); + JsonSerializer.Serialize(writer, formatTest.ByteProperty, options); + writer.WritePropertyName("date"); + JsonSerializer.Serialize(writer, formatTest.Date, options); + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, formatTest.DateTime, options); + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.DecimalProperty, options); + writer.WriteNumber("double", (int)formatTest.DoubleProperty); + writer.WriteNumber("float", (int)formatTest.FloatProperty); + writer.WriteNumber("int32", (int)formatTest.Int32); + writer.WriteNumber("int64", (int)formatTest.Int64); + writer.WriteNumber("integer", (int)formatTest.Integer); + writer.WriteNumber("number", (int)formatTest.Number); + writer.WriteString("password", formatTest.Password); + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + writer.WriteString("string", formatTest.StringProperty); + writer.WriteString("uuid", formatTest.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs index 95c52488446..3a8b95bb069 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,25 @@ namespace Org.OpenAPITools.Model /// /// Fruit /// - public partial class Fruit : IEquatable, IValidatableObject + public partial class Fruit : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// color - public Fruit(Apple apple, string color = default) + [JsonConstructor] + public Fruit(Apple apple, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = apple; Color = color; } @@ -45,8 +54,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public Fruit(Banana banana, string color = default) + [JsonConstructor] + public Fruit(Banana banana, string color) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Banana = banana; Color = color; } @@ -79,44 +98,6 @@ namespace Org.OpenAPITools.Model 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 Fruit).AreEqual; - } - - /// - /// Returns true if Fruit instances are equal - /// - /// Instance of Fruit to be compared - /// Boolean - public bool Equals(Fruit 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -133,13 +114,6 @@ namespace Org.OpenAPITools.Model /// public class FruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Fruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -152,9 +126,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple apple); @@ -165,10 +141,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -178,6 +157,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -198,6 +179,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", fruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs index f5abf198758..9418bf9a96c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// FruitReq /// - public partial class FruitReq : IEquatable, IValidatableObject + public partial class FruitReq : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public FruitReq(AppleReq appleReq) + [JsonConstructor] + internal FruitReq(AppleReq appleReq) { AppleReq = appleReq; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public FruitReq(BananaReq bananaReq) + [JsonConstructor] + internal FruitReq(BananaReq bananaReq) { BananaReq = bananaReq; } @@ -68,40 +69,6 @@ namespace Org.OpenAPITools.Model 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 FruitReq).AreEqual; - } - - /// - /// Returns true if FruitReq instances are equal - /// - /// Instance of FruitReq to be compared - /// Boolean - public bool Equals(FruitReq 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -118,13 +85,6 @@ namespace Org.OpenAPITools.Model /// public class FruitReqJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(FruitReq).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -137,9 +97,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReqReader = reader; bool appleReqDeserialized = Client.ClientUtils.TryDeserialize(ref appleReqReader, options, out AppleReq appleReq); @@ -149,16 +111,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -179,6 +146,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs index 3b4ac358673..cc28f46c42f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,7 +26,7 @@ namespace Org.OpenAPITools.Model /// /// GmFruit /// - public partial class GmFruit : IEquatable, IValidatableObject + public partial class GmFruit : IValidatableObject { /// /// Initializes a new instance of the class. @@ -35,8 +34,18 @@ namespace Org.OpenAPITools.Model /// /// /// color - public GmFruit(Apple apple, Banana banana, string color = default) + [JsonConstructor] + public GmFruit(Apple apple, Banana banana, string color) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException("color is a required property for GmFruit and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Apple = Apple; Banana = Banana; Color = color; @@ -70,44 +79,6 @@ namespace Org.OpenAPITools.Model 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 GmFruit).AreEqual; - } - - /// - /// Returns true if GmFruit instances are equal - /// - /// Instance of GmFruit to be compared - /// Boolean - public bool Equals(GmFruit 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; - if (this.Color != null) - { - hashCode = (hashCode * 59) + this.Color.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -124,13 +95,6 @@ namespace Org.OpenAPITools.Model /// public class GmFruitJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(GmFruit).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -143,9 +107,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader appleReader = reader; bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple apple); @@ -156,10 +122,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -169,6 +138,8 @@ namespace Org.OpenAPITools.Model case "color": color = reader.GetString(); break; + default: + break; } } } @@ -183,6 +154,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", gmFruit.Color); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index c880e6711ef..1557d82e538 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// GrandparentAnimal /// - public partial class GrandparentAnimal : IEquatable, IValidatableObject + public partial class GrandparentAnimal : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) + /// petType + [JsonConstructor] public GrandparentAnimal(string petType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (petType == null) throw new ArgumentNullException("petType is a required property for GrandparentAnimal and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + PetType = petType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 GrandparentAnimal).AreEqual; - } - - /// - /// Returns true if GrandparentAnimal instances are equal - /// - /// Instance of GrandparentAnimal to be compared - /// Boolean - public bool Equals(GrandparentAnimal 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; - if (this.PetType != null) - { - hashCode = (hashCode * 59) + this.PetType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -129,4 +93,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type GrandparentAnimal + /// + public class GrandparentAnimalJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override GrandparentAnimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string petType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "pet_type": + petType = reader.GetString(); + break; + default: + break; + } + } + } + + return new GrandparentAnimal(petType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", grandparentAnimal.PetType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 849a4886c31..c0e8044b40b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,8 +33,21 @@ namespace Org.OpenAPITools.Model /// /// bar /// foo - public HasOnlyReadOnly(string bar = default, string foo = default) + [JsonConstructor] + internal HasOnlyReadOnly(string bar, string foo) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for HasOnlyReadOnly and cannot be null."); + + if (foo == null) + throw new ArgumentNullException("foo is a required property for HasOnlyReadOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Foo = foo; } @@ -44,19 +56,19 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; private set; } + public string Foo { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -102,22 +114,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Foo != null) - { - hashCode = (hashCode * 59) + this.Foo.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -129,4 +132,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HasOnlyReadOnly + /// + public class HasOnlyReadOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HasOnlyReadOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string foo = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "foo": + foo = reader.GetString(); + break; + default: + break; + } + } + } + + return new HasOnlyReadOnly(bar, foo); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", hasOnlyReadOnly.Bar); + writer.WriteString("foo", hasOnlyReadOnly.Foo); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs index f66a3e132f4..2f0e472f639 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,12 +26,13 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class HealthCheckResult : IValidatableObject { /// /// Initializes a new instance of the class. /// /// nullableMessage + [JsonConstructor] public HealthCheckResult(string nullableMessage = default) { NullableMessage = nullableMessage; @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +63,6 @@ namespace Org.OpenAPITools.Model 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 HealthCheckResult).AreEqual; - } - - /// - /// Returns true if HealthCheckResult instances are equal - /// - /// Instance of HealthCheckResult to be compared - /// Boolean - public bool Equals(HealthCheckResult 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; - if (this.NullableMessage != null) - { - hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +74,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type HealthCheckResult + /// + public class HealthCheckResultJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override HealthCheckResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string nullableMessage = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "NullableMessage": + nullableMessage = reader.GetString(); + break; + default: + break; + } + } + } + + return new HealthCheckResult(nullableMessage); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index d1371b46bf3..45bfcd4f84b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// IsoscelesTriangle /// - public partial class IsoscelesTriangle : IEquatable, IValidatableObject + public partial class IsoscelesTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal IsoscelesTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -61,40 +61,6 @@ namespace Org.OpenAPITools.Model 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 IsoscelesTriangle).AreEqual; - } - - /// - /// Returns true if IsoscelesTriangle instances are equal - /// - /// Instance of IsoscelesTriangle to be compared - /// Boolean - public bool Equals(IsoscelesTriangle 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; - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -111,13 +77,6 @@ namespace Org.OpenAPITools.Model /// public class IsoscelesTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(IsoscelesTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -130,28 +89,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -166,6 +132,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs index 7a3e133f693..654d498a9cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// List /// - public partial class List : IEquatable, IValidatableObject + public partial class List : IValidatableObject { /// /// Initializes a new instance of the class. /// /// _123list - public List(string _123list = default) + [JsonConstructor] + public List(string _123list) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (_123list == null) + throw new ArgumentNullException("_123list is a required property for List and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + _123List = _123list; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 List).AreEqual; - } - - /// - /// Returns true if List instances are equal - /// - /// Instance of List to be compared - /// Boolean - public bool Equals(List 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; - if (this._123List != null) - { - hashCode = (hashCode * 59) + this._123List.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type List + /// + public class ListJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string _123list = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "123-list": + _123list = reader.GetString(); + break; + default: + break; + } + } + } + + return new List(_123list); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("123-list", list._123List); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs index f29770cdfe9..87e28b32ff1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Mammal /// - public partial class Mammal : IEquatable, IValidatableObject + public partial class Mammal : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Mammal(Whale whale) + [JsonConstructor] + internal Mammal(Whale whale) { Whale = whale; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Zebra zebra) + [JsonConstructor] + internal Mammal(Zebra zebra) { Zebra = zebra; } @@ -51,7 +52,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Mammal(Pig pig) + [JsonConstructor] + internal Mammal(Pig pig) { Pig = pig; } @@ -75,7 +77,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -89,44 +91,6 @@ namespace Org.OpenAPITools.Model 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 Mammal).AreEqual; - } - - /// - /// Returns true if Mammal instances are equal - /// - /// Instance of Mammal to be compared - /// Boolean - public bool Equals(Mammal 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -153,13 +117,6 @@ namespace Org.OpenAPITools.Model /// public class MammalJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Mammal).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -172,9 +129,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader whaleReader = reader; bool whaleDeserialized = Client.ClientUtils.TryDeserialize(ref whaleReader, options, out Whale whale); @@ -187,16 +146,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -220,6 +184,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs index 2cf624e2afb..777120531d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,40 @@ namespace Org.OpenAPITools.Model /// /// MapTest /// - public partial class MapTest : IEquatable, IValidatableObject + public partial class MapTest : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// mapMapOfString - /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) + /// mapMapOfString + /// mapOfEnumString + [JsonConstructor] + public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) { - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (mapMapOfString == null) + throw new ArgumentNullException("mapMapOfString is a required property for MapTest and cannot be null."); + + if (mapOfEnumString == null) + throw new ArgumentNullException("mapOfEnumString is a required property for MapTest and cannot be null."); + + if (directMap == null) + throw new ArgumentNullException("directMap is a required property for MapTest and cannot be null."); + + if (indirectMap == null) + throw new ArgumentNullException("indirectMap is a required property for MapTest and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DirectMap = directMap; IndirectMap = indirectMap; + MapMapOfString = mapMapOfString; + MapOfEnumString = mapOfEnumString; } /// @@ -52,28 +70,47 @@ namespace Org.OpenAPITools.Model /// /// Enum UPPER for value: UPPER /// - [EnumMember(Value = "UPPER")] UPPER = 1, /// /// Enum Lower for value: lower /// - [EnumMember(Value = "lower")] Lower = 2 } /// - /// Gets or Sets MapMapOfString + /// Returns a InnerEnum /// - [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + /// + /// + public static InnerEnum InnerEnumFromString(string value) + { + if (value == "UPPER") + return InnerEnum.UPPER; + + if (value == "lower") + return InnerEnum.Lower; + + throw new NotImplementedException($"Could not convert value to type InnerEnum: '{value}'"); + } /// - /// Gets or Sets MapOfEnumString + /// Returns equivalent json value /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + /// + /// + /// + 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 @@ -87,11 +124,23 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -101,68 +150,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); - sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); - sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as MapTest).AreEqual; - } - - /// - /// Returns true if MapTest instances are equal - /// - /// Instance of MapTest to be compared - /// Boolean - public bool Equals(MapTest 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; - if (this.MapMapOfString != null) - { - hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); - } - if (this.MapOfEnumString != null) - { - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); - } - if (this.DirectMap != null) - { - hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); - } - if (this.IndirectMap != null) - { - hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -174,4 +169,90 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MapTest + /// + public class MapTestJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MapTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Dictionary directMap = default; + Dictionary indirectMap = default; + Dictionary> mapMapOfString = default; + Dictionary mapOfEnumString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "direct_map": + directMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "indirect_map": + indirectMap = JsonSerializer.Deserialize>(ref reader, options); + break; + case "map_map_of_string": + mapMapOfString = JsonSerializer.Deserialize>>(ref reader, options); + break; + case "map_of_enum_string": + mapOfEnumString = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, options); + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, options); + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, options); + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 68b2ea60b78..4806980e331 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,27 +26,37 @@ namespace Org.OpenAPITools.Model /// /// MixedPropertiesAndAdditionalPropertiesClass /// - public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid /// dateTime /// map - public MixedPropertiesAndAdditionalPropertiesClass(Guid uuid = default, DateTime dateTime = default, Dictionary map = default) + /// uuid + [JsonConstructor] + public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid) { - Uuid = uuid; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (dateTime == null) + throw new ArgumentNullException("dateTime is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + + if (map == null) + throw new ArgumentNullException("map is a required property for MixedPropertiesAndAdditionalPropertiesClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + DateTime = dateTime; Map = map; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } - /// /// Gets or Sets DateTime /// @@ -60,11 +69,17 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("map")] public Dictionary Map { get; set; } + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,63 +89,13 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).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 MixedPropertiesAndAdditionalPropertiesClass).AreEqual; - } - - /// - /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal - /// - /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared - /// Boolean - public bool Equals(MixedPropertiesAndAdditionalPropertiesClass 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - if (this.DateTime != null) - { - hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); - } - if (this.Map != null) - { - hashCode = (hashCode * 59) + this.Map.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -142,4 +107,83 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type MixedPropertiesAndAdditionalPropertiesClass + /// + public class MixedPropertiesAndAdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + DateTime dateTime = default; + Dictionary map = default; + Guid uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "dateTime": + dateTime = JsonSerializer.Deserialize(ref reader, options); + break; + case "map": + map = JsonSerializer.Deserialize>(ref reader, options); + break; + case "uuid": + uuid = reader.GetGuid(); + break; + default: + break; + } + } + } + + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("dateTime"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.DateTime, options); + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, options); + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs index 6662b2edac4..eca0214cd89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,36 +26,49 @@ namespace Org.OpenAPITools.Model /// /// Model for testing model name starting with number /// - public partial class Model200Response : IEquatable, IValidatableObject + public partial class Model200Response : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// classProperty /// name - /// _class - public Model200Response(int name = default, string _class = default) + [JsonConstructor] + public Model200Response(string classProperty, int name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (name == null) + throw new ArgumentNullException("name is a required property for Model200Response and cannot be null."); + + if (classProperty == null) + throw new ArgumentNullException("classProperty is a required property for Model200Response and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ClassProperty = classProperty; Name = name; - Class = _class; } + /// + /// Gets or Sets ClassProperty + /// + [JsonPropertyName("class")] + public string ClassProperty { get; set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] public int Name { get; set; } - /// - /// Gets or Sets Class - /// - [JsonPropertyName("class")] - public string Class { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); + sb.Append(" ClassProperty: ").Append(ClassProperty).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Class: ").Append(Class).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 Model200Response).AreEqual; - } - - /// - /// Returns true if Model200Response instances are equal - /// - /// Instance of Model200Response to be compared - /// Boolean - public bool Equals(Model200Response 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) + this.Name.GetHashCode(); - if (this.Class != null) - { - hashCode = (hashCode * 59) + this.Class.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Model200Response + /// + public class Model200ResponseJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Model200Response Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string classProperty = default; + int name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "class": + classProperty = reader.GetString(); + break; + case "name": + name = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Model200Response(classProperty, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("class", model200Response.ClassProperty); + writer.WriteNumber("name", (int)model200Response.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs index 7bc5c681bbe..dc243ef72f6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,28 +26,38 @@ namespace Org.OpenAPITools.Model /// /// ModelClient /// - public partial class ModelClient : IEquatable, IValidatableObject + public partial class ModelClient : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// _client - public ModelClient(string _client = default) + /// clientProperty + [JsonConstructor] + public ModelClient(string clientProperty) { - _Client = _client; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (clientProperty == null) + throw new ArgumentNullException("clientProperty is a required property for ModelClient and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + _ClientProperty = clientProperty; } /// - /// Gets or Sets _Client + /// Gets or Sets _ClientProperty /// [JsonPropertyName("client")] - public string _Client { get; set; } + public string _ClientProperty { get; set; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -58,53 +67,11 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); - sb.Append(" _Client: ").Append(_Client).Append("\n"); + sb.Append(" _ClientProperty: ").Append(_ClientProperty).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 ModelClient).AreEqual; - } - - /// - /// Returns true if ModelClient instances are equal - /// - /// Instance of ModelClient to be compared - /// Boolean - public bool Equals(ModelClient 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; - if (this._Client != null) - { - hashCode = (hashCode * 59) + this._Client.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -116,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ModelClient + /// + public class ModelClientJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ModelClient Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string clientProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "client": + clientProperty = reader.GetString(); + break; + default: + break; + } + } + } + + return new ModelClient(clientProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("client", modelClient._ClientProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs index 95d35d993b2..3e927732b72 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,18 +31,34 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - /// nameProperty (required) - /// snakeCase + /// nameProperty /// property + /// snakeCase /// _123number - public Name(int nameProperty, int snakeCase = default, string property = default, int _123number = default) + [JsonConstructor] + public Name(int nameProperty, string property, int snakeCase, int _123number) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (nameProperty == null) throw new ArgumentNullException("nameProperty is a required property for Name and cannot be null."); + if (snakeCase == null) + throw new ArgumentNullException("snakeCase is a required property for Name and cannot be null."); + + if (property == null) + throw new ArgumentNullException("property is a required property for Name and cannot be null."); + + if (_123number == null) + throw new ArgumentNullException("_123number is a required property for Name and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + NameProperty = nameProperty; - SnakeCase = snakeCase; Property = property; + SnakeCase = snakeCase; _123Number = _123number; } @@ -53,29 +68,29 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("name")] public int NameProperty { get; set; } - /// - /// Gets or Sets SnakeCase - /// - [JsonPropertyName("snake_case")] - public int SnakeCase { get; private 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 _123Number /// [JsonPropertyName("123Number")] - public int _123Number { get; private set; } + public int _123Number { get; } /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -86,8 +101,8 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" NameProperty: ").Append(NameProperty).Append("\n"); - sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" _123Number: ").Append(_123Number).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -123,21 +138,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + this.NameProperty.GetHashCode(); - hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); - if (this.Property != null) - { - hashCode = (hashCode * 59) + this.Property.GetHashCode(); - } - hashCode = (hashCode * 59) + this._123Number.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + _123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -149,4 +156,86 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Name + /// + public class NameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Name Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int nameProperty = default; + string property = default; + int snakeCase = default; + int _123number = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "name": + nameProperty = reader.GetInt32(); + break; + case "property": + property = reader.GetString(); + break; + case "snake_case": + snakeCase = reader.GetInt32(); + break; + case "123Number": + _123number = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Name(nameProperty, property, snakeCase, _123number); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("name", (int)name.NameProperty); + writer.WriteString("property", name.Property); + writer.WriteNumber("snake_case", (int)name.SnakeCase); + writer.WriteNumber("123Number", (int)name._123Number); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs index 9bc37488229..0dbf928e051 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,50 +26,75 @@ namespace Org.OpenAPITools.Model /// /// NullableClass /// - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// integerProp - /// numberProp + /// arrayItemsNullable + /// objectItemsNullable + /// arrayAndItemsNullableProp + /// arrayNullableProp /// booleanProp - /// stringProp /// dateProp /// datetimeProp - /// arrayNullableProp - /// arrayAndItemsNullableProp - /// arrayItemsNullable - /// objectNullableProp + /// integerProp + /// numberProp /// objectAndItemsNullableProp - /// objectItemsNullable - public NullableClass(int? integerProp = default, decimal? numberProp = default, bool? booleanProp = default, string stringProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, List arrayNullableProp = default, List arrayAndItemsNullableProp = default, List arrayItemsNullable = default, Dictionary objectNullableProp = default, Dictionary objectAndItemsNullableProp = default, Dictionary objectItemsNullable = default) : base() + /// 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() { - IntegerProp = integerProp; - NumberProp = numberProp; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (arrayItemsNullable == null) + throw new ArgumentNullException("arrayItemsNullable is a required property for NullableClass and cannot be null."); + + if (objectItemsNullable == null) + throw new ArgumentNullException("objectItemsNullable is a required property for NullableClass and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ArrayItemsNullable = arrayItemsNullable; + ObjectItemsNullable = objectItemsNullable; + ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + ArrayNullableProp = arrayNullableProp; BooleanProp = booleanProp; - StringProp = stringProp; DateProp = dateProp; DatetimeProp = datetimeProp; - ArrayNullableProp = arrayNullableProp; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayItemsNullable = arrayItemsNullable; - ObjectNullableProp = objectNullableProp; + IntegerProp = integerProp; + NumberProp = numberProp; ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectItemsNullable = objectItemsNullable; + ObjectNullableProp = objectNullableProp; + StringProp = stringProp; } /// - /// Gets or Sets IntegerProp + /// Gets or Sets ArrayItemsNullable /// - [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get; set; } /// - /// Gets or Sets NumberProp + /// Gets or Sets ObjectItemsNullable /// - [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + [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 @@ -78,12 +102,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("boolean_prop")] public bool? BooleanProp { get; set; } - /// - /// Gets or Sets StringProp - /// - [JsonPropertyName("string_prop")] - public string StringProp { get; set; } - /// /// Gets or Sets DateProp /// @@ -97,28 +115,16 @@ namespace Org.OpenAPITools.Model public DateTime? DatetimeProp { get; set; } /// - /// Gets or Sets ArrayNullableProp + /// Gets or Sets IntegerProp /// - [JsonPropertyName("array_nullable_prop")] - public List ArrayNullableProp { get; set; } + [JsonPropertyName("integer_prop")] + public int? IntegerProp { get; set; } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Gets or Sets NumberProp /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List ArrayAndItemsNullableProp { get; set; } - - /// - /// Gets or Sets ArrayItemsNullable - /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } - - /// - /// Gets or Sets ObjectNullableProp - /// - [JsonPropertyName("object_nullable_prop")] - public Dictionary ObjectNullableProp { get; set; } + [JsonPropertyName("number_prop")] + public decimal? NumberProp { get; set; } /// /// Gets or Sets ObjectAndItemsNullableProp @@ -127,10 +133,16 @@ namespace Org.OpenAPITools.Model public Dictionary ObjectAndItemsNullableProp { get; set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ObjectNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("object_nullable_prop")] + public Dictionary ObjectNullableProp { get; set; } + + /// + /// Gets or Sets StringProp + /// + [JsonPropertyName("string_prop")] + public string StringProp { get; set; } /// /// Returns the string presentation of the object @@ -141,103 +153,21 @@ namespace Org.OpenAPITools.Model StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); - sb.Append(" NumberProp: ").Append(NumberProp).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(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); - sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); - sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).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(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" StringProp: ").Append(StringProp).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 NullableClass).AreEqual; - } - - /// - /// Returns true if NullableClass instances are equal - /// - /// Instance of NullableClass to be compared - /// Boolean - public bool Equals(NullableClass 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 = base.GetHashCode(); - if (this.IntegerProp != null) - { - hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); - } - if (this.NumberProp != null) - { - hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); - } - if (this.BooleanProp != null) - { - hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); - } - if (this.StringProp != null) - { - hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); - } - if (this.DateProp != null) - { - hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); - } - if (this.DatetimeProp != null) - { - hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); - } - if (this.ArrayNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); - } - if (this.ArrayAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); - } - if (this.ArrayItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); - } - if (this.ObjectNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); - } - if (this.ObjectAndItemsNullableProp != null) - { - hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); - } - if (this.ObjectItemsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -249,4 +179,145 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NullableClass + /// + public class NullableClassJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NullableClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "array_items_nullable": + arrayItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_items_nullable": + objectItemsNullable = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_and_items_nullable_prop": + arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "array_nullable_prop": + arrayNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "boolean_prop": + booleanProp = reader.GetBoolean(); + break; + case "date_prop": + dateProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "datetime_prop": + datetimeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "integer_prop": + if (reader.TokenType != JsonTokenType.Null) + integerProp = reader.GetInt32(); + break; + case "number_prop": + if (reader.TokenType != JsonTokenType.Null) + numberProp = reader.GetInt32(); + break; + case "object_and_items_nullable_prop": + objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "object_nullable_prop": + objectNullableProp = JsonSerializer.Deserialize>(ref reader, options); + break; + case "string_prop": + stringProp = reader.GetString(); + break; + default: + break; + } + } + } + + return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, options); + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, options); + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, options); + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, options); + if (nullableClass.BooleanProp != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); + else + writer.WriteNull("boolean_prop"); + writer.WritePropertyName("date_prop"); + JsonSerializer.Serialize(writer, nullableClass.DateProp, options); + writer.WritePropertyName("datetime_prop"); + JsonSerializer.Serialize(writer, nullableClass.DatetimeProp, options); + if (nullableClass.IntegerProp != null) + writer.WriteNumber("integer_prop", (int)nullableClass.IntegerProp.Value); + else + writer.WriteNull("integer_prop"); + if (nullableClass.NumberProp != null) + writer.WriteNumber("number_prop", (int)nullableClass.NumberProp.Value); + else + writer.WriteNull("number_prop"); + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, options); + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, options); + writer.WriteString("string_prop", nullableClass.StringProp); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs index 5ef1763454a..bcd4b60c1df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.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 : IEquatable, IValidatableObject + public partial class NullableShape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public NullableShape(Triangle triangle) + [JsonConstructor] + internal NullableShape(Triangle triangle) { Triangle = triangle; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public NullableShape(Quadrilateral quadrilateral) + [JsonConstructor] + internal NullableShape(Quadrilateral quadrilateral) { Quadrilateral = quadrilateral; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 NullableShape).AreEqual; - } - - /// - /// Returns true if NullableShape instances are equal - /// - /// Instance of NullableShape to be compared - /// Boolean - public bool Equals(NullableShape 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class NullableShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(NullableShape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs index 64f6395b603..035a084d727 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// NumberOnly /// - public partial class NumberOnly : IEquatable, IValidatableObject + public partial class NumberOnly : IValidatableObject { /// /// Initializes a new instance of the class. /// /// justNumber - public NumberOnly(decimal justNumber = default) + [JsonConstructor] + public NumberOnly(decimal justNumber) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (justNumber == null) + throw new ArgumentNullException("justNumber is a required property for NumberOnly and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + JustNumber = justNumber; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 NumberOnly).AreEqual; - } - - /// - /// Returns true if NumberOnly instances are equal - /// - /// Instance of NumberOnly to be compared - /// Boolean - public bool Equals(NumberOnly 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) + this.JustNumber.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type NumberOnly + /// + public class NumberOnlyJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override NumberOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal justNumber = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "JustNumber": + justNumber = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new NumberOnly(justNumber); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("JustNumber", (int)numberOnly.JustNumber); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 817af80674c..26f0d3f5fa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,43 +26,42 @@ namespace Org.OpenAPITools.Model /// /// ObjectWithDeprecatedFields /// - public partial class ObjectWithDeprecatedFields : IEquatable, IValidatableObject + public partial class ObjectWithDeprecatedFields : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// uuid - /// id - /// deprecatedRef /// bars - public ObjectWithDeprecatedFields(string uuid = default, decimal id = default, DeprecatedObject deprecatedRef = default, List bars = default) + /// deprecatedRef + /// id + /// uuid + [JsonConstructor] + public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) { - Uuid = uuid; - Id = id; - DeprecatedRef = deprecatedRef; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (uuid == null) + throw new ArgumentNullException("uuid is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (id == null) + throw new ArgumentNullException("id is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (deprecatedRef == null) + throw new ArgumentNullException("deprecatedRef is a required property for ObjectWithDeprecatedFields and cannot be null."); + + if (bars == null) + throw new ArgumentNullException("bars is a required property for ObjectWithDeprecatedFields and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bars = bars; + DeprecatedRef = deprecatedRef; + Id = id; + Uuid = uuid; } - /// - /// Gets or Sets Uuid - /// - [JsonPropertyName("uuid")] - public string Uuid { get; set; } - - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - [Obsolete] - public decimal Id { get; set; } - - /// - /// Gets or Sets DeprecatedRef - /// - [JsonPropertyName("deprecatedRef")] - [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } - /// /// Gets or Sets Bars /// @@ -71,11 +69,31 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -85,65 +103,14 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); - sb.Append(" Uuid: ").Append(Uuid).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" DeprecatedRef: ").Append(DeprecatedRef).Append("\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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as ObjectWithDeprecatedFields).AreEqual; - } - - /// - /// Returns true if ObjectWithDeprecatedFields instances are equal - /// - /// Instance of ObjectWithDeprecatedFields to be compared - /// Boolean - public bool Equals(ObjectWithDeprecatedFields 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; - if (this.Uuid != null) - { - hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.DeprecatedRef != null) - { - hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); - } - if (this.Bars != null) - { - hashCode = (hashCode * 59) + this.Bars.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -155,4 +122,88 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ObjectWithDeprecatedFields + /// + public class ObjectWithDeprecatedFieldsJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List bars = default; + DeprecatedObject deprecatedRef = default; + decimal id = default; + string uuid = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bars": + bars = JsonSerializer.Deserialize>(ref reader, options); + break; + case "deprecatedRef": + deprecatedRef = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt32(); + break; + case "uuid": + uuid = reader.GetString(); + break; + default: + break; + } + } + } + + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, options); + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, options); + writer.WriteNumber("id", (int)objectWithDeprecatedFields.Id); + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs index 2fef14a9c59..62777359e73 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,7 +26,7 @@ namespace Org.OpenAPITools.Model /// /// Order /// - public partial class Order : IEquatable, IValidatableObject + public partial class Order : IValidatableObject { /// /// Initializes a new instance of the class. @@ -38,8 +37,33 @@ namespace Org.OpenAPITools.Model /// shipDate /// Order Status /// complete (default to false) - public Order(long id = default, long petId = default, int quantity = default, DateTime shipDate = default, StatusEnum status = default, bool complete = false) + [JsonConstructor] + public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Order and cannot be null."); + + if (petId == null) + throw new ArgumentNullException("petId is a required property for Order and cannot be null."); + + if (quantity == null) + throw new ArgumentNullException("quantity is a required property for Order and cannot be null."); + + if (shipDate == null) + throw new ArgumentNullException("shipDate is a required property for Order and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Order and cannot be null."); + + if (complete == null) + throw new ArgumentNullException("complete is a required property for Order and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; PetId = petId; Quantity = quantity; @@ -57,23 +81,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "placed") + return StatusEnum.Placed; + + if (value == "approved") + return StatusEnum.Approved; + + if (value == "delivered") + return StatusEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -115,7 +175,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -135,53 +195,6 @@ namespace Org.OpenAPITools.Model 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 Order).AreEqual; - } - - /// - /// Returns true if Order instances are equal - /// - /// Instance of Order to be compared - /// Boolean - public bool Equals(Order 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) + this.Id.GetHashCode(); - hashCode = (hashCode * 59) + this.PetId.GetHashCode(); - hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); - if (this.ShipDate != null) - { - hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - hashCode = (hashCode * 59) + this.Complete.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -193,4 +206,102 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Order + /// + public class OrderJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Order Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + long petId = default; + int quantity = default; + DateTime shipDate = default; + Order.StatusEnum status = default; + bool complete = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "petId": + petId = reader.GetInt64(); + break; + case "quantity": + quantity = reader.GetInt32(); + break; + case "shipDate": + shipDate = JsonSerializer.Deserialize(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Order.StatusEnumFromString(statusRawValue); + break; + case "complete": + complete = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Order(id, petId, quantity, shipDate, status, complete); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)order.Id); + writer.WriteNumber("petId", (int)order.PetId); + writer.WriteNumber("quantity", (int)order.Quantity); + writer.WritePropertyName("shipDate"); + JsonSerializer.Serialize(writer, order.ShipDate, options); + var statusRawValue = Order.StatusEnumToJsonValue(order.Status); + if (statusRawValue != null) + writer.WriteString("status", statusRawValue); + else + writer.WriteNull("status"); + writer.WriteBoolean("complete", order.Complete); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs index 390b308657e..13f5f05b588 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,43 @@ namespace Org.OpenAPITools.Model /// /// OuterComposite /// - public partial class OuterComposite : IEquatable, IValidatableObject + public partial class OuterComposite : IValidatableObject { /// /// Initializes a new instance of the class. /// + /// myBoolean /// myNumber /// myString - /// myBoolean - public OuterComposite(decimal myNumber = default, string myString = default, bool myBoolean = default) + [JsonConstructor] + public OuterComposite(bool myBoolean, decimal myNumber, string myString) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (myNumber == null) + throw new ArgumentNullException("myNumber is a required property for OuterComposite and cannot be null."); + + if (myString == null) + throw new ArgumentNullException("myString is a required property for OuterComposite and cannot be null."); + + if (myBoolean == null) + throw new ArgumentNullException("myBoolean is a required property for OuterComposite and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + MyBoolean = myBoolean; MyNumber = myNumber; MyString = myString; - MyBoolean = myBoolean; } + /// + /// Gets or Sets MyBoolean + /// + [JsonPropertyName("my_boolean")] + public bool MyBoolean { get; set; } + /// /// Gets or Sets MyNumber /// @@ -54,17 +75,11 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("my_string")] public string MyString { get; set; } - /// - /// Gets or Sets MyBoolean - /// - [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } - /// /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -74,57 +89,13 @@ namespace Org.OpenAPITools.Model { 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(" MyBoolean: ").Append(MyBoolean).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 OuterComposite).AreEqual; - } - - /// - /// Returns true if OuterComposite instances are equal - /// - /// Instance of OuterComposite to be compared - /// Boolean - public bool Equals(OuterComposite 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) + this.MyNumber.GetHashCode(); - if (this.MyString != null) - { - hashCode = (hashCode * 59) + this.MyString.GetHashCode(); - } - hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -136,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type OuterComposite + /// + public class OuterCompositeJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override OuterComposite Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + bool myBoolean = default; + decimal myNumber = default; + string myString = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "my_boolean": + myBoolean = reader.GetBoolean(); + break; + case "my_number": + myNumber = reader.GetInt32(); + break; + case "my_string": + myString = reader.GetString(); + break; + default: + break; + } + } + } + + return new OuterComposite(myBoolean, myNumber, myString); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); + writer.WriteNumber("my_number", (int)outerComposite.MyNumber); + writer.WriteString("my_string", outerComposite.MyString); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs index 8496c413326..31e3049659b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumConverter : JsonConverter + { + public static OuterEnum FromString(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnum: '{value}'"); + } + + public static OuterEnum? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnum.Placed; + + if (value == "approved") + return OuterEnum.Approved; + + if (value == "delivered") + return OuterEnum.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnum? result = OuterEnumConverter.FromString(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()); + } + } + + public class OuterEnumNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnum from the Json object + /// + /// + /// + /// + /// + public override OuterEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnum? result = OuterEnumConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index b0f9d099e27..d3f7db5b4fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -32,20 +31,129 @@ namespace Org.OpenAPITools.Model /// /// Enum Placed for value: placed /// - [EnumMember(Value = "placed")] Placed = 1, /// /// Enum Approved for value: approved /// - [EnumMember(Value = "approved")] Approved = 2, /// /// Enum Delivered for value: delivered /// - [EnumMember(Value = "delivered")] Delivered = 3 } + + public class OuterEnumDefaultValueConverter : JsonConverter + { + public static OuterEnumDefaultValue FromString(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnumDefaultValue: '{value}'"); + } + + public static OuterEnumDefaultValue? FromStringOrDefault(string value) + { + if (value == "placed") + return OuterEnumDefaultValue.Placed; + + if (value == "approved") + return OuterEnumDefaultValue.Approved; + + if (value == "delivered") + return OuterEnumDefaultValue.Delivered; + + return null; + } + + 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}'"); + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumDefaultValue? result = OuterEnumDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 56069346c2e..e704048b8c3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -45,4 +44,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerConverter : JsonConverter + { + public static OuterEnumInteger FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumInteger: '{value}'"); + } + + public static OuterEnumInteger? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumInteger.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumInteger.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumInteger.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumInteger value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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()); + } + } + + public class OuterEnumIntegerNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumInteger from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumInteger? result = OuterEnumIntegerConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index e80f88f51f3..8e559a7975b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -45,4 +44,107 @@ namespace Org.OpenAPITools.Model NUMBER_2 = 2 } + + public class OuterEnumIntegerDefaultValueConverter : JsonConverter + { + public static OuterEnumIntegerDefaultValue FromString(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumIntegerDefaultValue: '{value}'"); + } + + public static OuterEnumIntegerDefaultValue? FromStringOrDefault(string value) + { + if (value == (0).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value == (1).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value == (2).ToString()) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + return null; + } + + public static int ToJsonValue(OuterEnumIntegerDefaultValue value) + { + return (int) value; + } + + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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()); + } + } + + public class OuterEnumIntegerDefaultValueNullableConverter : JsonConverter + { + /// + /// Returns a OuterEnumIntegerDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string rawValue = reader.GetString(); + + if (rawValue == null) + return null; + + OuterEnumIntegerDefaultValue? result = OuterEnumIntegerDefaultValueConverter.FromString(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"); + } + } + } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs index 244b3b93840..fa0bfd0120e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// ParentPet /// - public partial class ParentPet : GrandparentAnimal, IEquatable + public partial class ParentPet : GrandparentAnimal, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// petType (required) - public ParentPet(string petType) : base(petType) + /// petType + [JsonConstructor] + internal ParentPet(string petType) : base(petType) { } @@ -49,40 +49,6 @@ namespace Org.OpenAPITools.Model 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 ParentPet).AreEqual; - } - - /// - /// Returns true if ParentPet instances are equal - /// - /// Instance of ParentPet to be compared - /// Boolean - public bool Equals(ParentPet 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 = base.GetHashCode(); - return hashCode; - } - } - } /// @@ -90,13 +56,6 @@ namespace Org.OpenAPITools.Model /// public class ParentPetJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ParentPet).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -109,17 +68,22 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + string petType = default; while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -129,6 +93,8 @@ namespace Org.OpenAPITools.Model case "pet_type": petType = reader.GetString(); break; + default: + break; } } } @@ -143,6 +109,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("pet_type", parentPet.PetType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs index 0091def60e5..ad0e1587799 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,31 +26,50 @@ namespace Org.OpenAPITools.Model /// /// Pet /// - public partial class Pet : IEquatable, IValidatableObject + public partial class Pet : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// name (required) - /// photoUrls (required) - /// id /// category - /// tags + /// id + /// name + /// photoUrls /// pet status in the store - public Pet(string name, List photoUrls, long id = default, Category category = default, List tags = default, StatusEnum status = default) + /// tags + [JsonConstructor] + public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Pet and cannot be null."); + + if (category == null) + throw new ArgumentNullException("category is a required property for Pet and cannot be null."); + if (name == null) throw new ArgumentNullException("name is a required property for Pet and cannot be null."); if (photoUrls == null) throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null."); + if (tags == null) + throw new ArgumentNullException("tags is a required property for Pet and cannot be null."); + + if (status == null) + throw new ArgumentNullException("status is a required property for Pet and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Category = category; + Id = id; Name = name; PhotoUrls = photoUrls; - Id = id; - Category = category; - Tags = tags; Status = status; + Tags = tags; } /// @@ -63,23 +81,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Available for value: available /// - [EnumMember(Value = "available")] Available = 1, /// /// Enum Pending for value: pending /// - [EnumMember(Value = "pending")] Pending = 2, /// /// Enum Sold for value: sold /// - [EnumMember(Value = "sold")] Sold = 3 } + /// + /// Returns a StatusEnum + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value == "available") + return StatusEnum.Available; + + if (value == "pending") + return StatusEnum.Pending; + + if (value == "sold") + return StatusEnum.Sold; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -87,6 +141,18 @@ namespace Org.OpenAPITools.Model [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 /// @@ -99,18 +165,6 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("photoUrls")] public List PhotoUrls { get; set; } - /// - /// Gets or Sets Id - /// - [JsonPropertyName("id")] - public long Id { get; set; } - - /// - /// Gets or Sets Category - /// - [JsonPropertyName("category")] - public Category Category { get; set; } - /// /// Gets or Sets Tags /// @@ -121,7 +175,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -131,72 +185,16 @@ namespace Org.OpenAPITools.Model { 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(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Tags: ").Append(Tags).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as Pet).AreEqual; - } - - /// - /// Returns true if Pet instances are equal - /// - /// Instance of Pet to be compared - /// Boolean - public bool Equals(Pet 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; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.PhotoUrls != null) - { - hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Id.GetHashCode(); - if (this.Category != null) - { - hashCode = (hashCode * 59) + this.Category.GetHashCode(); - } - if (this.Tags != null) - { - hashCode = (hashCode * 59) + this.Tags.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -208,4 +206,104 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Pet + /// + public class PetJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Pet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Category category = default; + long id = default; + string name = default; + List photoUrls = default; + Pet.StatusEnum status = default; + List tags = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "category": + category = JsonSerializer.Deserialize(ref reader, options); + break; + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + case "photoUrls": + photoUrls = JsonSerializer.Deserialize>(ref reader, options); + break; + case "status": + string statusRawValue = reader.GetString(); + status = Pet.StatusEnumFromString(statusRawValue); + break; + case "tags": + tags = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new Pet(category, id, name, photoUrls, status, tags); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, options); + writer.WriteNumber("id", (int)pet.Id); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); + JsonSerializer.Serialize(writer, pet.PhotoUrls, options); + 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, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs index 4eb947b0140..b2292d1331e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Pig /// - public partial class Pig : IEquatable, IValidatableObject + public partial class Pig : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Pig(BasquePig basquePig) + [JsonConstructor] + internal Pig(BasquePig basquePig) { BasquePig = basquePig; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Pig(DanishPig danishPig) + [JsonConstructor] + internal Pig(DanishPig danishPig) { DanishPig = danishPig; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 Pig).AreEqual; - } - - /// - /// Returns true if Pig instances are equal - /// - /// Instance of Pig to be compared - /// Boolean - public bool Equals(Pig 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class PigJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Pig).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader basquePigReader = reader; bool basquePigDeserialized = Client.ClientUtils.TryDeserialize(ref basquePigReader, options, out BasquePig basquePig); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index 1152b4e63f4..e7a03145456 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// PolymorphicProperty /// - public partial class PolymorphicProperty : IEquatable, IValidatableObject + public partial class PolymorphicProperty : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(bool _bool) + [JsonConstructor] + internal PolymorphicProperty(bool _bool) { Bool = _bool; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(string _string) + [JsonConstructor] + internal PolymorphicProperty(string _string) { String = _string; } @@ -51,7 +52,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(Object _object) + [JsonConstructor] + internal PolymorphicProperty(Object _object) { Object = _object; } @@ -60,7 +62,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public PolymorphicProperty(List liststring) + [JsonConstructor] + internal PolymorphicProperty(List liststring) { Liststring = liststring; } @@ -89,7 +92,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -103,44 +106,6 @@ namespace Org.OpenAPITools.Model 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 PolymorphicProperty).AreEqual; - } - - /// - /// Returns true if PolymorphicProperty instances are equal - /// - /// Instance of PolymorphicProperty to be compared - /// Boolean - public bool Equals(PolymorphicProperty 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -157,13 +122,6 @@ namespace Org.OpenAPITools.Model /// public class PolymorphicPropertyJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(PolymorphicProperty).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -176,9 +134,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader _boolReader = reader; bool _boolDeserialized = Client.ClientUtils.TryDeserialize(ref _boolReader, options, out bool _bool); @@ -194,16 +154,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -230,6 +195,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs index 47e72d44ab6..d1dcd22b8e3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,13 +26,14 @@ namespace Org.OpenAPITools.Model /// /// Quadrilateral /// - public partial class Quadrilateral : IEquatable, IValidatableObject + public partial class Quadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - public Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) + [JsonConstructor] + internal Quadrilateral(SimpleQuadrilateral simpleQuadrilateral) { SimpleQuadrilateral = simpleQuadrilateral; } @@ -42,7 +42,8 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - public Quadrilateral(ComplexQuadrilateral complexQuadrilateral) + [JsonConstructor] + internal Quadrilateral(ComplexQuadrilateral complexQuadrilateral) { ComplexQuadrilateral = complexQuadrilateral; } @@ -61,7 +62,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -75,44 +76,6 @@ namespace Org.OpenAPITools.Model 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 Quadrilateral).AreEqual; - } - - /// - /// Returns true if Quadrilateral instances are equal - /// - /// Instance of Quadrilateral to be compared - /// Boolean - public bool Equals(Quadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,13 +102,6 @@ namespace Org.OpenAPITools.Model /// public class QuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Quadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -158,9 +114,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader simpleQuadrilateralReader = reader; bool simpleQuadrilateralDeserialized = Client.ClientUtils.TryDeserialize(ref simpleQuadrilateralReader, options, out SimpleQuadrilateral simpleQuadrilateral); @@ -170,16 +128,21 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -200,6 +163,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 046b9050ba0..6faf1ddd505 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// QuadrilateralInterface /// - public partial class QuadrilateralInterface : IEquatable, IValidatableObject + public partial class QuadrilateralInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public QuadrilateralInterface(string quadrilateralType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) throw new ArgumentNullException("quadrilateralType is a required property for QuadrilateralInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + QuadrilateralType = quadrilateralType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 QuadrilateralInterface).AreEqual; - } - - /// - /// Returns true if QuadrilateralInterface instances are equal - /// - /// Instance of QuadrilateralInterface to be compared - /// Boolean - public bool Equals(QuadrilateralInterface 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type QuadrilateralInterface + /// + public class QuadrilateralInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override QuadrilateralInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string quadrilateralType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "quadrilateralType": + quadrilateralType = reader.GetString(); + break; + default: + break; + } + } + } + + return new QuadrilateralInterface(quadrilateralType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 3589a97ed6c..d81d94a35fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -34,8 +33,21 @@ namespace Org.OpenAPITools.Model /// /// bar /// baz - public ReadOnlyFirst(string bar = default, string baz = default) + [JsonConstructor] + public ReadOnlyFirst(string bar, string baz) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (bar == null) + throw new ArgumentNullException("bar is a required property for ReadOnlyFirst and cannot be null."); + + if (baz == null) + throw new ArgumentNullException("baz is a required property for ReadOnlyFirst and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Bar = bar; Baz = baz; } @@ -44,7 +56,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; private set; } + public string Bar { get; } /// /// Gets or Sets Baz @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -102,22 +114,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - if (this.Bar != null) - { - hashCode = (hashCode * 59) + this.Bar.GetHashCode(); - } - if (this.Baz != null) - { - hashCode = (hashCode * 59) + this.Baz.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + return hashCode; } } - /// /// To validate all properties of the instance /// @@ -129,4 +131,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ReadOnlyFirst + /// + public class ReadOnlyFirstJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ReadOnlyFirst Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string bar = default; + string baz = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "bar": + bar = reader.GetString(); + break; + case "baz": + baz = reader.GetString(); + break; + default: + break; + } + } + } + + return new ReadOnlyFirst(bar, baz); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("bar", readOnlyFirst.Bar); + writer.WriteString("baz", readOnlyFirst.Baz); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs index 2b73710ad81..b560dc903b9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Model for testing reserved words /// - public partial class Return : IEquatable, IValidatableObject + public partial class Return : IValidatableObject { /// /// Initializes a new instance of the class. /// /// returnProperty - public Return(int returnProperty = default) + [JsonConstructor] + public Return(int returnProperty) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (returnProperty == null) + throw new ArgumentNullException("returnProperty is a required property for Return and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ReturnProperty = returnProperty; } @@ -48,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -63,45 +72,6 @@ namespace Org.OpenAPITools.Model 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 Return).AreEqual; - } - - /// - /// Returns true if Return instances are equal - /// - /// Instance of Return to be compared - /// Boolean - public bool Equals(Return 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) + this.ReturnProperty.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -113,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Return + /// + public class ReturnJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Return Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int returnProperty = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "return": + returnProperty = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Return(returnProperty); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Return _return, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("return", (int)_return.ReturnProperty); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 72568e1e01b..7654a4f8a09 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// ScaleneTriangle /// - public partial class ScaleneTriangle : IEquatable, IValidatableObject + public partial class ScaleneTriangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) + [JsonConstructor] + internal ScaleneTriangle(ShapeInterface shapeInterface, TriangleInterface triangleInterface) { ShapeInterface = shapeInterface; TriangleInterface = triangleInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 ScaleneTriangle).AreEqual; - } - - /// - /// Returns true if ScaleneTriangle instances are equal - /// - /// Instance of ScaleneTriangle to be compared - /// Boolean - public bool Equals(ScaleneTriangle 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class ScaleneTriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ScaleneTriangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader triangleInterfaceReader = reader; - bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref triangleInterfaceReader, options, out TriangleInterface triangleInterface); + bool triangleInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out TriangleInterface triangleInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs index e2cf8fb7cce..7412f32e61d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// Shape /// - public partial class Shape : IEquatable, IValidatableObject + public partial class Shape : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -47,11 +53,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public Shape(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for Shape and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -77,7 +90,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -92,48 +105,6 @@ namespace Org.OpenAPITools.Model 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 Shape).AreEqual; - } - - /// - /// Returns true if Shape instances are equal - /// - /// Instance of Shape to be compared - /// Boolean - public bool Equals(Shape 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -160,13 +131,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Shape).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -179,9 +143,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -192,10 +158,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -205,6 +174,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -225,6 +196,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shape.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index 5d0ab8ec9c7..b6a27e5efcc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// ShapeInterface /// - public partial class ShapeInterface : IEquatable, IValidatableObject + public partial class ShapeInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// shapeType (required) + /// shapeType + [JsonConstructor] public ShapeInterface(string shapeType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) throw new ArgumentNullException("shapeType is a required property for ShapeInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ShapeType = shapeType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 ShapeInterface).AreEqual; - } - - /// - /// Returns true if ShapeInterface instances are equal - /// - /// Instance of ShapeInterface to be compared - /// Boolean - public bool Equals(ShapeInterface 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type ShapeInterface + /// + public class ShapeInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ShapeInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string shapeType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "shapeType": + shapeType = reader.GetString(); + break; + default: + break; + } + } + } + + return new ShapeInterface(shapeType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", shapeInterface.ShapeType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 375f4d49076..64971919ee7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. /// - public partial class ShapeOrNull : IEquatable, IValidatableObject + public partial class ShapeOrNull : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Triangle triangle, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Triangle = triangle; QuadrilateralType = quadrilateralType; @@ -47,11 +53,18 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// quadrilateralType (required) + /// quadrilateralType + [JsonConstructor] public ShapeOrNull(Quadrilateral quadrilateral, string quadrilateralType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (quadrilateralType == null) - throw new ArgumentNullException("quadrilateralType is a required property for ShapeOrNull and cannot be null."); + throw new ArgumentNullException(nameof(QuadrilateralType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' Quadrilateral = quadrilateral; QuadrilateralType = quadrilateralType; @@ -77,7 +90,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -92,48 +105,6 @@ namespace Org.OpenAPITools.Model 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 ShapeOrNull).AreEqual; - } - - /// - /// Returns true if ShapeOrNull instances are equal - /// - /// Instance of ShapeOrNull to be compared - /// Boolean - public bool Equals(ShapeOrNull 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; - if (this.QuadrilateralType != null) - { - hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -160,13 +131,6 @@ namespace Org.OpenAPITools.Model /// public class ShapeOrNullJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(ShapeOrNull).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -179,9 +143,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader triangleReader = reader; bool triangleDeserialized = Client.ClientUtils.TryDeserialize(ref triangleReader, options, out Triangle triangle); @@ -192,10 +158,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -205,6 +174,8 @@ namespace Org.OpenAPITools.Model case "quadrilateralType": quadrilateralType = reader.GetString(); break; + default: + break; } } } @@ -225,6 +196,13 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("quadrilateralType", shapeOrNull.QuadrilateralType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index ee6d8ef1823..feb4017722a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,14 +26,15 @@ namespace Org.OpenAPITools.Model /// /// SimpleQuadrilateral /// - public partial class SimpleQuadrilateral : IEquatable, IValidatableObject + public partial class SimpleQuadrilateral : IValidatableObject { /// /// Initializes a new instance of the class. /// /// /// - public SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) + [JsonConstructor] + internal SimpleQuadrilateral(ShapeInterface shapeInterface, QuadrilateralInterface quadrilateralInterface) { ShapeInterface = shapeInterface; QuadrilateralInterface = quadrilateralInterface; @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -68,44 +68,6 @@ namespace Org.OpenAPITools.Model 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 SimpleQuadrilateral).AreEqual; - } - - /// - /// Returns true if SimpleQuadrilateral instances are equal - /// - /// Instance of SimpleQuadrilateral to be compared - /// Boolean - public bool Equals(SimpleQuadrilateral 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; - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -122,13 +84,6 @@ namespace Org.OpenAPITools.Model /// public class SimpleQuadrilateralJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(SimpleQuadrilateral).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -141,28 +96,35 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader shapeInterfaceReader = reader; - bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref shapeInterfaceReader, options, out ShapeInterface shapeInterface); + bool shapeInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ShapeInterface shapeInterface); Utf8JsonReader quadrilateralInterfaceReader = reader; - bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref quadrilateralInterfaceReader, options, out QuadrilateralInterface quadrilateralInterface); + bool quadrilateralInterfaceDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out QuadrilateralInterface quadrilateralInterface); while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { + default: + break; } } } @@ -177,6 +139,12 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs index 35fc0efd1c5..db141494908 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,24 +26,31 @@ namespace Org.OpenAPITools.Model /// /// SpecialModelName /// - public partial class SpecialModelName : IEquatable, IValidatableObject + public partial class SpecialModelName : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// specialPropertyName /// specialModelNameProperty - public SpecialModelName(long specialPropertyName = default, string specialModelNameProperty = default) + /// specialPropertyName + [JsonConstructor] + public SpecialModelName(string specialModelNameProperty, long specialPropertyName) { - SpecialPropertyName = specialPropertyName; - SpecialModelNameProperty = specialModelNameProperty; - } +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' - /// - /// Gets or Sets SpecialPropertyName - /// - [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + if (specialPropertyName == null) + throw new ArgumentNullException("specialPropertyName is a required property for SpecialModelName and cannot be null."); + + if (specialModelNameProperty == null) + throw new ArgumentNullException("specialModelNameProperty is a required property for SpecialModelName and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + SpecialModelNameProperty = specialModelNameProperty; + SpecialPropertyName = specialPropertyName; + } /// /// Gets or Sets SpecialModelNameProperty @@ -52,11 +58,17 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("_special_model.name_")] public string SpecialModelNameProperty { 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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,55 +78,12 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); - sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" SpecialModelNameProperty: ").Append(SpecialModelNameProperty).Append("\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).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 SpecialModelName).AreEqual; - } - - /// - /// Returns true if SpecialModelName instances are equal - /// - /// Instance of SpecialModelName to be compared - /// Boolean - public bool Equals(SpecialModelName 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) + this.SpecialPropertyName.GetHashCode(); - if (this.SpecialModelNameProperty != null) - { - hashCode = (hashCode * 59) + this.SpecialModelNameProperty.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type SpecialModelName + /// + public class SpecialModelNameJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override SpecialModelName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string specialModelNameProperty = default; + long specialPropertyName = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "_special_model.name_": + specialModelNameProperty = reader.GetString(); + break; + case "$special[property.name]": + specialPropertyName = reader.GetInt64(); + break; + default: + break; + } + } + } + + return new SpecialModelName(specialModelNameProperty, specialPropertyName); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("_special_model.name_", specialModelName.SpecialModelNameProperty); + writer.WriteNumber("$special[property.name]", (int)specialModelName.SpecialPropertyName); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs index fcc38c0b3ac..51a80012fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,15 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Tag /// - public partial class Tag : IEquatable, IValidatableObject + public partial class Tag : IValidatableObject { /// /// Initializes a new instance of the class. /// /// id /// name - public Tag(long id = default, string name = default) + [JsonConstructor] + public Tag(long id, string name) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for Tag and cannot be null."); + + if (name == null) + throw new ArgumentNullException("name is a required property for Tag and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Id = id; Name = name; } @@ -56,7 +68,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -72,49 +84,6 @@ namespace Org.OpenAPITools.Model 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 Tag).AreEqual; - } - - /// - /// Returns true if Tag instances are equal - /// - /// Instance of Tag to be compared - /// Boolean - public bool Equals(Tag 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) + this.Id.GetHashCode(); - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -126,4 +95,76 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Tag + /// + public class TagJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Tag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + long id = default; + string name = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "id": + id = reader.GetInt64(); + break; + case "name": + name = reader.GetString(); + break; + default: + break; + } + } + } + + return new Tag(id, name); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("id", (int)tag.Id); + writer.WriteString("name", tag.Name); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs index f799b7c43bb..6f5eae3cca6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,21 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Triangle /// - public partial class Triangle : IEquatable, IValidatableObject + public partial class Triangle : IValidatableObject { /// /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(EquilateralTriangle equilateralTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' EquilateralTriangle = equilateralTriangle; ShapeType = shapeType; @@ -52,15 +58,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(IsoscelesTriangle isoscelesTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' IsoscelesTriangle = isoscelesTriangle; ShapeType = shapeType; @@ -71,15 +84,22 @@ namespace Org.OpenAPITools.Model /// Initializes a new instance of the class. /// /// - /// shapeType (required) - /// triangleType (required) + /// shapeType + /// triangleType + [JsonConstructor] public Triangle(ScaleneTriangle scaleneTriangle, string shapeType, string triangleType) { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (shapeType == null) - throw new ArgumentNullException("shapeType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(ShapeType)); if (triangleType == null) - throw new ArgumentNullException("triangleType is a required property for Triangle and cannot be null."); + throw new ArgumentNullException(nameof(TriangleType)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' ScaleneTriangle = scaleneTriangle; ShapeType = shapeType; @@ -117,7 +137,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -133,52 +153,6 @@ namespace Org.OpenAPITools.Model 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 Triangle).AreEqual; - } - - /// - /// Returns true if Triangle instances are equal - /// - /// Instance of Triangle to be compared - /// Boolean - public bool Equals(Triangle 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; - if (this.ShapeType != null) - { - hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); - } - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -205,13 +179,6 @@ namespace Org.OpenAPITools.Model /// public class TriangleJsonConverter : JsonConverter { - /// - /// Returns a boolean if the type is compatible with this converter. - /// - /// - /// - public override bool CanConvert(Type typeToConvert) => typeof(Triangle).IsAssignableFrom(typeToConvert); - /// /// A Json reader. /// @@ -224,9 +191,11 @@ namespace Org.OpenAPITools.Model { int currentDepth = reader.CurrentDepth; - if (reader.TokenType != JsonTokenType.StartObject) + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + JsonTokenType startingTokenType = reader.TokenType; + Utf8JsonReader equilateralTriangleReader = reader; bool equilateralTriangleDeserialized = Client.ClientUtils.TryDeserialize(ref equilateralTriangleReader, options, out EquilateralTriangle equilateralTriangle); @@ -241,10 +210,13 @@ namespace Org.OpenAPITools.Model while (reader.Read()) { - if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; - if (reader.TokenType == JsonTokenType.PropertyName) + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) { string propertyName = reader.GetString(); reader.Read(); @@ -257,6 +229,8 @@ namespace Org.OpenAPITools.Model case "triangleType": triangleType = reader.GetString(); break; + default: + break; } } } @@ -280,6 +254,14 @@ namespace Org.OpenAPITools.Model /// /// /// - public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) => throw new NotImplementedException(); + public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("shapeType", triangle.ShapeType); + writer.WriteString("triangleType", triangle.TriangleType); + + writer.WriteEndObject(); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index f7b06bf05a9..882d2b9e429 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,17 +26,24 @@ namespace Org.OpenAPITools.Model /// /// TriangleInterface /// - public partial class TriangleInterface : IEquatable, IValidatableObject + public partial class TriangleInterface : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// triangleType (required) + /// triangleType + [JsonConstructor] public TriangleInterface(string triangleType) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + if (triangleType == null) throw new ArgumentNullException("triangleType is a required property for TriangleInterface and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + TriangleType = triangleType; } @@ -51,7 +57,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -66,48 +72,6 @@ namespace Org.OpenAPITools.Model 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 TriangleInterface).AreEqual; - } - - /// - /// Returns true if TriangleInterface instances are equal - /// - /// Instance of TriangleInterface to be compared - /// Boolean - public bool Equals(TriangleInterface 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; - if (this.TriangleType != null) - { - hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -119,4 +83,71 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type TriangleInterface + /// + public class TriangleInterfaceJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override TriangleInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string triangleType = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "triangleType": + triangleType = reader.GetString(); + break; + default: + break; + } + } + } + + return new TriangleInterface(triangleType); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("triangleType", triangleInterface.TriangleType); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs index 38a79e975db..a92270295ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,50 +26,78 @@ namespace Org.OpenAPITools.Model /// /// User /// - public partial class User : IEquatable, IValidatableObject + public partial class User : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// id - /// username - /// firstName - /// lastName /// 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 - /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// 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. - public User(long id = default, string username = default, string firstName = default, string lastName = default, string email = default, string password = default, string phone = default, int userStatus = default, Object objectWithNoDeclaredProps = default, Object objectWithNoDeclaredPropsNullable = default, Object anyTypeProp = default, Object anyTypePropNullable = default) + /// 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) { - Id = id; - Username = username; - FirstName = firstName; - LastName = lastName; +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (id == null) + throw new ArgumentNullException("id is a required property for User and cannot be null."); + + if (username == null) + throw new ArgumentNullException("username is a required property for User and cannot be null."); + + if (firstName == null) + throw new ArgumentNullException("firstName is a required property for User and cannot be null."); + + if (lastName == null) + throw new ArgumentNullException("lastName is a required property for User and cannot be null."); + + if (email == null) + throw new ArgumentNullException("email is a required property for User and cannot be null."); + + if (password == null) + throw new ArgumentNullException("password is a required property for User and cannot be null."); + + if (phone == null) + throw new ArgumentNullException("phone is a required property for User and cannot be null."); + + if (userStatus == null) + throw new ArgumentNullException("userStatus is a required property for User and cannot be null."); + + if (objectWithNoDeclaredProps == null) + throw new ArgumentNullException("objectWithNoDeclaredProps is a required property for User and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + Email = email; + FirstName = firstName; + Id = id; + LastName = lastName; + ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; Password = password; Phone = phone; UserStatus = userStatus; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + Username = username; AnyTypeProp = anyTypeProp; AnyTypePropNullable = anyTypePropNullable; + ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; } /// - /// Gets or Sets Id + /// Gets or Sets Email /// - [JsonPropertyName("id")] - public long Id { get; set; } - - /// - /// Gets or Sets Username - /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonPropertyName("email")] + public string Email { get; set; } /// /// Gets or Sets FirstName @@ -78,6 +105,12 @@ namespace Org.OpenAPITools.Model [JsonPropertyName("firstName")] public string FirstName { get; set; } + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + /// /// Gets or Sets LastName /// @@ -85,10 +118,11 @@ namespace Org.OpenAPITools.Model public string LastName { get; set; } /// - /// Gets or Sets Email + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// - [JsonPropertyName("email")] - public string Email { get; set; } + /// 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 @@ -110,18 +144,10 @@ namespace Org.OpenAPITools.Model public int UserStatus { get; set; } /// - /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// Gets or Sets Username /// - /// 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; } - - /// - /// 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; } + [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 @@ -137,11 +163,18 @@ namespace Org.OpenAPITools.Model [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; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -151,102 +184,22 @@ namespace Org.OpenAPITools.Model { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" FirstName: ").Append(FirstName).Append("\n"); - sb.Append(" LastName: ").Append(LastName).Append("\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(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).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(); } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as User).AreEqual; - } - - /// - /// Returns true if User instances are equal - /// - /// Instance of User to be compared - /// Boolean - public bool Equals(User 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) + this.Id.GetHashCode(); - if (this.Username != null) - { - hashCode = (hashCode * 59) + this.Username.GetHashCode(); - } - if (this.FirstName != null) - { - hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); - } - if (this.LastName != null) - { - hashCode = (hashCode * 59) + this.LastName.GetHashCode(); - } - if (this.Email != null) - { - hashCode = (hashCode * 59) + this.Email.GetHashCode(); - } - if (this.Password != null) - { - hashCode = (hashCode * 59) + this.Password.GetHashCode(); - } - if (this.Phone != null) - { - hashCode = (hashCode * 59) + this.Phone.GetHashCode(); - } - hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); - if (this.ObjectWithNoDeclaredProps != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); - } - if (this.ObjectWithNoDeclaredPropsNullable != null) - { - hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); - } - if (this.AnyTypeProp != null) - { - hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); - } - if (this.AnyTypePropNullable != null) - { - hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -258,4 +211,130 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type User + /// + public class UserJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override User Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.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 (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "email": + email = reader.GetString(); + break; + case "firstName": + firstName = reader.GetString(); + break; + case "id": + id = reader.GetInt64(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "objectWithNoDeclaredProps": + objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref reader, options); + break; + case "password": + password = reader.GetString(); + break; + case "phone": + phone = reader.GetString(); + break; + case "userStatus": + userStatus = reader.GetInt32(); + break; + case "username": + username = reader.GetString(); + break; + case "anyTypeProp": + anyTypeProp = JsonSerializer.Deserialize(ref reader, options); + break; + case "anyTypePropNullable": + anyTypePropNullable = JsonSerializer.Deserialize(ref reader, options); + break; + case "objectWithNoDeclaredPropsNullable": + objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref reader, options); + break; + default: + break; + } + } + } + + return new User(email, firstName, id, lastName, objectWithNoDeclaredProps, password, phone, userStatus, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("email", user.Email); + writer.WriteString("firstName", user.FirstName); + writer.WriteNumber("id", (int)user.Id); + writer.WriteString("lastName", user.LastName); + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, options); + writer.WriteString("password", user.Password); + writer.WriteString("phone", user.Phone); + writer.WriteNumber("userStatus", (int)user.UserStatus); + writer.WriteString("username", user.Username); + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, options); + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, options); + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, options); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs index 57c3ddbd8df..598bedad22c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,19 +26,32 @@ namespace Org.OpenAPITools.Model /// /// Whale /// - public partial class Whale : IEquatable, IValidatableObject + public partial class Whale : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// hasBaleen /// hasTeeth - public Whale(string className, bool hasBaleen = default, bool hasTeeth = default) + [JsonConstructor] + public Whale(string className, bool hasBaleen, bool hasTeeth) { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (hasBaleen == null) + throw new ArgumentNullException("hasBaleen is a required property for Whale and cannot be null."); + + if (hasTeeth == null) + throw new ArgumentNullException("hasTeeth is a required property for Whale and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Whale and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; HasBaleen = hasBaleen; HasTeeth = hasTeeth; @@ -67,7 +79,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -84,50 +96,6 @@ namespace Org.OpenAPITools.Model 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 Whale).AreEqual; - } - - /// - /// Returns true if Whale instances are equal - /// - /// Instance of Whale to be compared - /// Boolean - public bool Equals(Whale 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; - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); - hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -139,4 +107,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Whale + /// + public class WhaleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Whale Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + bool hasBaleen = default; + bool hasTeeth = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "hasBaleen": + hasBaleen = reader.GetBoolean(); + break; + case "hasTeeth": + hasTeeth = reader.GetBoolean(); + break; + default: + break; + } + } + } + + return new Whale(className, hasBaleen, hasTeeth); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", whale.ClassName); + writer.WriteBoolean("hasBaleen", whale.HasBaleen); + writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs index 452c2fe8b71..df74e95ec6e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -14,7 +14,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; -using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; @@ -27,18 +26,28 @@ namespace Org.OpenAPITools.Model /// /// Zebra /// - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : Dictionary, IValidatableObject { /// /// Initializes a new instance of the class. /// - /// className (required) + /// className /// type - public Zebra(string className, TypeEnum type = default) : base() + [JsonConstructor] + public Zebra(string className, TypeEnum type) : base() { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (type == null) + throw new ArgumentNullException("type is a required property for Zebra and cannot be null."); + if (className == null) throw new ArgumentNullException("className is a required property for Zebra and cannot be null."); +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + ClassName = className; Type = type; } @@ -51,23 +60,59 @@ namespace Org.OpenAPITools.Model /// /// Enum Plains for value: plains /// - [EnumMember(Value = "plains")] Plains = 1, /// /// Enum Mountain for value: mountain /// - [EnumMember(Value = "mountain")] Mountain = 2, /// /// Enum Grevys for value: grevys /// - [EnumMember(Value = "grevys")] Grevys = 3 } + /// + /// Returns a TypeEnum + /// + /// + /// + public static TypeEnum TypeEnumFromString(string value) + { + if (value == "plains") + return TypeEnum.Plains; + + if (value == "mountain") + return TypeEnum.Mountain; + + if (value == "grevys") + return TypeEnum.Grevys; + + throw new NotImplementedException($"Could not convert value to type TypeEnum: '{value}'"); + } + + /// + /// Returns equivalent 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 /// @@ -84,7 +129,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets additional properties /// [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); + public Dictionary AdditionalProperties { get; } = new Dictionary(); /// /// Returns the string presentation of the object @@ -101,49 +146,6 @@ namespace Org.OpenAPITools.Model 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 Zebra).AreEqual; - } - - /// - /// Returns true if Zebra instances are equal - /// - /// Instance of Zebra to be compared - /// Boolean - public bool Equals(Zebra 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 = base.GetHashCode(); - if (this.ClassName != null) - { - hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); - } - hashCode = (hashCode * 59) + this.Type.GetHashCode(); - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - /// /// To validate all properties of the instance /// @@ -155,4 +157,81 @@ namespace Org.OpenAPITools.Model } } + /// + /// A Json converter for type Zebra + /// + public class ZebraJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Zebra Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string className = default; + Zebra.TypeEnum type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "className": + className = reader.GetString(); + break; + case "type": + string typeRawValue = reader.GetString(); + type = Zebra.TypeEnumFromString(typeRawValue); + break; + default: + break; + } + } + } + + return new Zebra(className, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("className", zebra.ClassName); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); + if (typeRawValue != null) + writer.WriteString("type", typeRawValue); + else + writer.WriteNull("type"); + + writer.WriteEndObject(); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md new file mode 100644 index 00000000000..e5abd8bceaa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md @@ -0,0 +1,260 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=netstandard2.0', + 'validatable=true', + 'nullableReferenceTypes=', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + '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 Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.Call123TestSpecialTagsWithHttpInfoAsync("todo"); + } + + 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 Org.OpenAPITools.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 +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 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: + + +### 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 + + +### bearer_test + + +- **Type**: Bearer Authentication + + +### http_basic_test + + +- **Type**: HTTP basic authentication + + +### http_signature_test + + + + +### 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 + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## 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: +- 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: Org.OpenAPITools +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: netstandard2.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-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 4ec90f4eafd..5fa12ee8933 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,13 +8,12 @@ - + - + - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 866b572467b..8dd131b6d22 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,13 +8,12 @@ - + - + - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f92a4564282..d708a4dd9b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,13 +9,12 @@ - + - + - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f75257161b7..6e71720a940 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -16,5 +16,4 @@ -