[csharp-netcore] Adds ability to inherit api (#13797)

* refactor nrt annotation

* enable nrt by default in .net6.0+

* use shorter nrt annotation

* build samples

* removed debugging lines

* fixed model and operatoin constructors

* reverted a commented line for comparison

* upgraded to System.Text.Json

* build samples

* build samples

* deleted samples to remove old files

* bug fixes

* bug fixes

* added cumpulsory property to codegen

* build samples

* fixed bug

* fixed bug

* fixes

* removed bugged code that wasnt needed

* build samples

* restored sorting and default values for required params

* fixed bugs in comparison

* fixed sort comparators

* recreate tests

* build samples...again...

* removed debugging line breaks

* simplified constructor signature

* inject json options

* build samples...again...

* build samples

* add support for composed primitives

* build samples

* build all samples

* avoid reserved words

* restored a file

* multiple fixes

* bug fixes

* bug fixes

* api clients now transient, added EventHub

* bug fix

* bug fix

* added ability to inherit api

* added ability to inherit api

* bug fix

* added requiredAndNotNullable

* added custom serialization

* added request info to error handler

* added OrDefault for enum parsing

* fixed DateTime? deserialization

* added support for server override

* added IServiceCollection to host builder extensions

* improve cookie support

* bug fixes

* fixed spacing

* fixed content type header

* fixed spacing

* removed reference to newtonsoft

* bug fixes in deserialization

* resolved conflicts

* removed postProcessAllModels code now present in abstract

* added a comment with url to an issue

* removed unneeded code

* removed change that should be another pr

* build and update samples

* reduce number of files modified

* reduce number of files modified

* delete and build samples

* delete and build samples

* fixed property name issue

* fixed CodegenModel collection properties

* avoid a conflict

* avoid a conflict

* add a todo

* added todo

* fixed circular reference

* small changes

* synced with other branches

* commented some code for now

* copied samples from master

* changed mustache templates

* build samples

* fixed invalid property names

* rebuild samples

* rebuild samples

* fixed casing issue

* resolved conflicts

* fixed bug in resolving conflicts

* removed default api, users can handle that if required

* removed default api, users can handle that if required

* build samples......again....

* addressed comment

* addressed comment

* addressed comment

* addressed comment

* build samples
This commit is contained in:
devhl-labs 2022-12-09 05:01:54 -05:00 committed by GitHub
parent a57fb9e109
commit c3b9bd7459
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
721 changed files with 34847 additions and 20341 deletions

View File

@ -48,6 +48,7 @@ public class CodegenOperation {
public List<CodegenParameter> cookieParams = new ArrayList<CodegenParameter>(); public List<CodegenParameter> cookieParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> requiredParams = new ArrayList<CodegenParameter>(); public List<CodegenParameter> requiredParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> optionalParams = new ArrayList<CodegenParameter>(); public List<CodegenParameter> optionalParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> requiredAndNotNullableParams = new ArrayList<CodegenParameter>();
public List<CodegenSecurity> authMethods; public List<CodegenSecurity> authMethods;
public List<Tag> tags; public List<Tag> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>(); public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
@ -157,6 +158,10 @@ public class CodegenOperation {
return nonEmpty(optionalParams); return nonEmpty(optionalParams);
} }
public boolean getHasRequiredAndNotNullableParams() {
return nonEmpty(requiredAndNotNullableParams);
}
/** /**
* Check if there's at least one required parameter * Check if there's at least one required parameter
* *
@ -364,6 +369,7 @@ public class CodegenOperation {
sb.append(", cookieParams=").append(cookieParams); sb.append(", cookieParams=").append(cookieParams);
sb.append(", requiredParams=").append(requiredParams); sb.append(", requiredParams=").append(requiredParams);
sb.append(", optionalParams=").append(optionalParams); sb.append(", optionalParams=").append(optionalParams);
sb.append(", requiredAndNotNullableParams=").append(requiredAndNotNullableParams);
sb.append(", authMethods=").append(authMethods); sb.append(", authMethods=").append(authMethods);
sb.append(", tags=").append(tags); sb.append(", tags=").append(tags);
sb.append(", responses=").append(responses); sb.append(", responses=").append(responses);
@ -442,6 +448,7 @@ public class CodegenOperation {
Objects.equals(cookieParams, that.cookieParams) && Objects.equals(cookieParams, that.cookieParams) &&
Objects.equals(requiredParams, that.requiredParams) && Objects.equals(requiredParams, that.requiredParams) &&
Objects.equals(optionalParams, that.optionalParams) && Objects.equals(optionalParams, that.optionalParams) &&
Objects.equals(requiredAndNotNullableParams, that.requiredAndNotNullableParams) &&
Objects.equals(authMethods, that.authMethods) && Objects.equals(authMethods, that.authMethods) &&
Objects.equals(tags, that.tags) && Objects.equals(tags, that.tags) &&
Objects.equals(responses, that.responses) && Objects.equals(responses, that.responses) &&
@ -471,6 +478,6 @@ public class CodegenOperation {
pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, returnProperty, optionalParams, pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, returnProperty, optionalParams,
authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs, authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs,
vendorExtensions, nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, vendorExtensions, nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase,
operationIdSnakeCase, hasErrorResponseObject); operationIdSnakeCase, hasErrorResponseObject, requiredAndNotNullableParams);
} }
} }

View File

@ -763,10 +763,14 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
this.requiredVars = requiredVars; this.requiredVars = requiredVars;
} }
public boolean compulsory(){ public boolean requiredAndNotNullable(){
return required && !isNullable; return required && !isNullable;
} }
public boolean notRequiredOrIsNullable() {
return !required || isNullable;
}
@Override @Override
public boolean getIsNull() { public boolean getIsNull() {
return isNull; return isNull;

View File

@ -505,7 +505,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
return required; return required;
} }
public boolean compulsory() { public boolean requiredAndNotNullable() {
return getRequired() && !isNullable; return getRequired() && !isNullable;
} }

View File

@ -4332,6 +4332,7 @@ public class DefaultCodegen implements CodegenConfig {
List<CodegenParameter> formParams = new ArrayList<>(); List<CodegenParameter> formParams = new ArrayList<>();
List<CodegenParameter> requiredParams = new ArrayList<>(); List<CodegenParameter> requiredParams = new ArrayList<>();
List<CodegenParameter> optionalParams = new ArrayList<>(); List<CodegenParameter> optionalParams = new ArrayList<>();
List<CodegenParameter> requiredAndNotNullableParams = new ArrayList<>();
CodegenParameter bodyParam = null; CodegenParameter bodyParam = null;
RequestBody requestBody = operation.getRequestBody(); RequestBody requestBody = operation.getRequestBody();
@ -4441,6 +4442,10 @@ public class DefaultCodegen implements CodegenConfig {
optionalParams.add(cp.copy()); optionalParams.add(cp.copy());
op.hasOptionalParams = true; op.hasOptionalParams = true;
} }
if (cp.requiredAndNotNullable()) {
requiredAndNotNullableParams.add(cp.copy());
}
} }
// add imports to operation import tag // add imports to operation import tag
@ -4477,6 +4482,7 @@ public class DefaultCodegen implements CodegenConfig {
op.formParams = formParams; op.formParams = formParams;
op.requiredParams = requiredParams; op.requiredParams = requiredParams;
op.optionalParams = optionalParams; op.optionalParams = optionalParams;
op.requiredAndNotNullableParams = requiredAndNotNullableParams;
op.externalDocs = operation.getExternalDocs(); op.externalDocs = operation.getExternalDocs();
// legacy support // legacy support
op.nickname = op.operationId; op.nickname = op.operationId;

View File

@ -400,19 +400,35 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
// avoid breaking changes // avoid breaking changes
if (GENERICHOST.equals(getLibrary())) { if (GENERICHOST.equals(getLibrary())) {
Comparator<CodegenProperty> comparatorByRequiredAndDefault = propertyComparatorByRequired.thenComparing(propertyComparatorByDefaultValue);
Collections.sort(codegenModel.vars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.vars, propertyComparatorByName);
Collections.sort(codegenModel.allVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.allVars, propertyComparatorByName);
Collections.sort(codegenModel.requiredVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.requiredVars, propertyComparatorByName);
Collections.sort(codegenModel.optionalVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.optionalVars, propertyComparatorByName);
Collections.sort(codegenModel.readOnlyVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.readOnlyVars, propertyComparatorByName);
Collections.sort(codegenModel.readWriteVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.readWriteVars, propertyComparatorByName);
Collections.sort(codegenModel.parentVars, comparatorByRequiredAndDefault); Collections.sort(codegenModel.parentVars, propertyComparatorByName);
Comparator<CodegenProperty> 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; return codegenModel;
} }
public static Comparator<CodegenProperty> propertyComparatorByName = new Comparator<CodegenProperty>() {
@Override
public int compare(CodegenProperty one, CodegenProperty another) {
return one.name.compareTo(another.name);
}
};
public static Comparator<CodegenProperty> propertyComparatorByDefaultValue = new Comparator<CodegenProperty>() { public static Comparator<CodegenProperty> propertyComparatorByDefaultValue = new Comparator<CodegenProperty>() {
@Override @Override
public int compare(CodegenProperty one, CodegenProperty another) { public int compare(CodegenProperty one, CodegenProperty another) {
@ -425,18 +441,25 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
} }
}; };
public static Comparator<CodegenProperty> propertyComparatorByRequired = new Comparator<CodegenProperty>() { public static Comparator<CodegenProperty> propertyComparatorByNullable = new Comparator<CodegenProperty>() {
@Override @Override
public int compare(CodegenProperty one, CodegenProperty another) { public int compare(CodegenProperty one, CodegenProperty another) {
if (one.required == another.required) if (one.isNullable == another.isNullable)
return 0; return 0;
else if (Boolean.TRUE.equals(one.required)) else if (Boolean.FALSE.equals(one.isNullable))
return -1; return -1;
else else
return 1; return 1;
} }
}; };
public static Comparator<CodegenParameter> parameterComparatorByDataType = new Comparator<CodegenParameter>() {
@Override
public int compare(CodegenParameter one, CodegenParameter another) {
return one.dataType.compareTo(another.dataType);
}
};
public static Comparator<CodegenParameter> parameterComparatorByDefaultValue = new Comparator<CodegenParameter>() { public static Comparator<CodegenParameter> parameterComparatorByDefaultValue = new Comparator<CodegenParameter>() {
@Override @Override
public int compare(CodegenParameter one, CodegenParameter another) { 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")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authPackageDir, "OAuthFlow.cs"));
} }
} }
addTestInstructions();
} }
public void setClientPackage(String clientPackage) { public void setClientPackage(String clientPackage) {
@ -823,45 +844,34 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
return op; return op;
} }
Comparator<CodegenParameter> comparatorByRequiredAndDefault = parameterComparatorByRequired.thenComparing(parameterComparatorByDefaultValue); Collections.sort(op.allParams, parameterComparatorByDataType);
Collections.sort(op.allParams, comparatorByRequiredAndDefault); Collections.sort(op.bodyParams, parameterComparatorByDataType);
Collections.sort(op.bodyParams, comparatorByRequiredAndDefault); Collections.sort(op.pathParams, parameterComparatorByDataType);
Collections.sort(op.pathParams, comparatorByRequiredAndDefault); Collections.sort(op.queryParams, parameterComparatorByDataType);
Collections.sort(op.queryParams, comparatorByRequiredAndDefault); Collections.sort(op.headerParams, parameterComparatorByDataType);
Collections.sort(op.headerParams, comparatorByRequiredAndDefault); Collections.sort(op.implicitHeadersParams, parameterComparatorByDataType);
Collections.sort(op.implicitHeadersParams, comparatorByRequiredAndDefault); Collections.sort(op.formParams, parameterComparatorByDataType);
Collections.sort(op.formParams, comparatorByRequiredAndDefault); Collections.sort(op.cookieParams, parameterComparatorByDataType);
Collections.sort(op.cookieParams, comparatorByRequiredAndDefault); Collections.sort(op.requiredParams, parameterComparatorByDataType);
Collections.sort(op.requiredParams, comparatorByRequiredAndDefault); Collections.sort(op.optionalParams, parameterComparatorByDataType);
Collections.sort(op.optionalParams, comparatorByRequiredAndDefault); Collections.sort(op.requiredAndNotNullableParams, parameterComparatorByDataType);
Comparator<CodegenParameter> 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; 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, public void addSupportingFiles(final String clientPackageDir, final String packageFolder,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) { final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) {
supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); 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")); supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs"));
} }
public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageFolder, public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageDir,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) { final AtomicReference<Boolean> 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("TokenProvider`1.mustache", clientPackageDir, "TokenProvider`1.cs"));
supportingFiles.add(new SupportingFile("RateLimitProvider`1.mustache", clientPackageDir, "RateLimitProvider`1.cs")); supportingFiles.add(new SupportingFile("RateLimitProvider`1.mustache", clientPackageDir, "RateLimitProvider`1.cs"));
supportingFiles.add(new SupportingFile("TokenContainer`1.mustache", clientPackageDir, "TokenContainer`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("ApiResponse`1.mustache", clientPackageDir, "ApiResponse`1.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
supportingFiles.add(new SupportingFile("HostConfiguration.mustache", clientPackageDir, "HostConfiguration.cs")); supportingFiles.add(new SupportingFile("HostConfiguration.mustache", clientPackageDir, "HostConfiguration.cs"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("ApiFactory.mustache", clientPackageDir, "ApiFactory.cs"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "docs" + File.separator + "scripts", "git_push.sh")); supportingFiles.add(new SupportingFile("DateTimeJsonConverter.mustache", clientPackageDir, "DateTimeJsonConverter.cs"));
supportingFiles.add(new SupportingFile("git_push.ps1.mustache", "docs" + File.separator + "scripts", "git_push.ps1")); supportingFiles.add(new SupportingFile("DateTimeNullableJsonConverter.mustache", clientPackageDir, "DateTimeNullableJsonConverter.cs"));
// 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("ApiResponseEventArgs.mustache", clientPackageDir, "ApiResponseEventArgs.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("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(); String apiTestFolder = testFolder + File.separator + testPackageName() + File.separator + apiPackage();
if (Boolean.FALSE.equals(excludeTests.get())) { 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")); supportingFiles.add(new SupportingFile("DependencyInjectionTests.mustache", apiTestFolder, "DependencyInjectionTests.cs"));
// do not overwrite test file that already exists // 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 * 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 * 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 // every c# generator should definitely want this, or we should fix the issue
// still, lets avoid breaking changes :( // still, lets avoid breaking changes :(
if (Boolean.FALSE.equals(GENERICHOST.equals(getLibrary()))){ 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; 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. * Removes properties from a model which are also defined in a composed class.
* *

View File

@ -6,7 +6,7 @@
{{/nrt}} {{/nrt}}
using System; using System;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// API Exception /// API Exception

View File

@ -0,0 +1,49 @@
using System;
using Microsoft.Extensions.DependencyInjection;
namespace {{packageName}}.{{clientPackage}}
{
/// <summary>
/// An IApiFactory interface
/// </summary>
{{>visibility}} interface IApiFactory
{
/// <summary>
/// A method to create an IApi of type IResult
/// </summary>
/// <typeparam name="IResult"></typeparam>
/// <returns></returns>
IResult Create<IResult>() where IResult : {{interfacePrefix}}{{apiPackage}}.IApi;
}
/// <summary>
/// An ApiFactory
/// </summary>
{{>visibility}} class ApiFactory : IApiFactory
{
/// <summary>
/// The service provider
/// </summary>
public IServiceProvider Services { get; }
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <param name="services"></param>
public ApiFactory(IServiceProvider services)
{
Services = services;
}
/// <summary>
/// A method to create an IApi of type IResult
/// </summary>
/// <typeparam name="IResult"></typeparam>
/// <returns></returns>
public IResult Create<IResult>() where IResult : {{interfacePrefix}}{{apiPackage}}.IApi
{
return Services.GetRequiredService<IResult>();
}
}
}

View File

@ -6,12 +6,12 @@
{{/nrt}} {{/nrt}}
using System; using System;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A token constructed from an apiKey. /// A token constructed from an apiKey.
/// </summary> /// </summary>
public class ApiKeyToken : TokenBase {{>visibility}} class ApiKeyToken : TokenBase
{ {
private string _raw; private string _raw;
@ -20,22 +20,12 @@ namespace {{packageName}}.Client
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="prefix"></param> /// <param name="prefix"></param>
/// <param name="timeout"></param> /// <param name="timeout"></param>
public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout)
{ {
_raw = $"{ prefix }{ value }"; _raw = $"{ prefix }{ value }";
} }
/// <summary>
/// Places the token in the cookie.
/// </summary>
/// <param name="request"></param>
/// <param name="cookieName"></param>
public virtual void UseInCookie(System.Net.Http.HttpRequestMessage request, string cookieName)
{
request.Headers.Add("Cookie", $"{ cookieName }=_raw");
}
/// <summary> /// <summary>
/// Places the token in the header. /// Places the token in the header.
/// </summary> /// </summary>

View File

@ -1,46 +1,57 @@
using System; using System;
using System.Net; using System.Net;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Useful for tracking server health. /// Useful for tracking server health.
/// </summary> /// </summary>
public class ApiResponseEventArgs : EventArgs {{>visibility}} class ApiResponseEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// The time the request was sent. /// The time the request was sent.
/// </summary> /// </summary>
public DateTime RequestedAt { get; } public DateTime RequestedAt { get; }
/// <summary> /// <summary>
/// The time the response was received. /// The time the response was received.
/// </summary> /// </summary>
public DateTime ReceivedAt { get; } public DateTime ReceivedAt { get; }
/// <summary> /// <summary>
/// The HttpStatusCode received. /// The HttpStatusCode received.
/// </summary> /// </summary>
public HttpStatusCode HttpStatus { get; } public HttpStatusCode HttpStatus { get; }
/// <summary> /// <summary>
/// The path requested. /// The path requested.
/// </summary> /// </summary>
public string Path { get; } public string PathFormat { get; }
/// <summary> /// <summary>
/// The elapsed time from request to response. /// The elapsed time from request to response.
/// </summary> /// </summary>
public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt;
/// <summary>
/// The path
/// </summary>
public string Path { get; }
/// <summary> /// <summary>
/// The event args used to track server health. /// The event args used to track server health.
/// </summary> /// </summary>
/// <param name="requestedAt"></param> /// <param name="requestedAt"></param>
/// <param name="receivedAt"></param> /// <param name="receivedAt"></param>
/// <param name="httpStatus"></param> /// <param name="httpStatus"></param>
/// <param name="pathFormat"></param>
/// <param name="path"></param> /// <param name="path"></param>
public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string path) public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path)
{ {
RequestedAt = requestedAt; RequestedAt = requestedAt;
ReceivedAt = receivedAt; ReceivedAt = receivedAt;
HttpStatus = httpStatus; HttpStatus = httpStatus;
PathFormat = pathFormat;
Path = path; Path = path;
} }
} }

View File

@ -8,12 +8,12 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Provides a non-generic contract for the ApiResponse wrapper. /// Provides a non-generic contract for the ApiResponse wrapper.
/// </summary> /// </summary>
public interface IApiResponse {{>visibility}} interface IApiResponse
{ {
/// <summary> /// <summary>
/// The data type of <see cref="Data"/> /// The data type of <see cref="Data"/>
@ -30,6 +30,11 @@ namespace {{packageName}}.Client
/// The raw content of this response /// The raw content of this response
/// </summary> /// </summary>
string RawContent { get; } string RawContent { get; }
/// <summary>
/// The DateTime when the request was retrieved.
/// </summary>
DateTime DownloadedAt { get; }
} }
/// <summary> /// <summary>
@ -37,13 +42,11 @@ namespace {{packageName}}.Client
/// </summary> /// </summary>
{{>visibility}} partial class ApiResponse<T> : IApiResponse {{>visibility}} partial class ApiResponse<T> : IApiResponse
{ {
#region Properties
/// <summary> /// <summary>
/// The deserialized content /// The deserialized content
/// </summary> /// </summary>
{{! .net 3.1 does not support unconstrained nullable T }} {{! .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; }
/// <summary> /// <summary>
/// Gets or sets the status code (HTTP status code) /// Gets or sets the status code (HTTP status code)
@ -79,7 +82,10 @@ namespace {{packageName}}.Client
/// </summary> /// </summary>
public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } public System.Net.Http.Headers.HttpResponseHeaders Headers { get; }
#endregion Properties /// <summary>
/// The DateTime when the request was retrieved.
/// </summary>
public DateTime DownloadedAt { get; } = DateTime.UtcNow;
/// <summary> /// <summary>
/// Construct the response using an HttpResponseMessage /// Construct the response using an HttpResponseMessage

View File

@ -3,14 +3,15 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using {{packageName}}.Client;{{#hasImport}} using {{packageName}}.{{clientPackage}};{{#hasImport}}
using {{packageName}}.{{modelPackage}};{{/hasImport}} using {{packageName}}.{{modelPackage}};{{/hasImport}}
using {{packageName}}.Extensions;
{{{testInstructions}}} {{>testInstructions}}
namespace {{packageName}}.Test.Api namespace {{packageName}}.Test.{{apiPackage}}
{ {
/// <summary> /// <summary>
/// Base class for API tests /// Base class for API tests
@ -25,7 +26,7 @@ namespace {{packageName}}.Test.Api
} }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) 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["<token>"], timeout: TimeSpan.FromSeconds(1)); {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration["<token>"], timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);

View File

@ -9,12 +9,12 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A token constructed from a username and password. /// A token constructed from a username and password.
/// </summary> /// </summary>
public class BasicToken : TokenBase {{>visibility}} class BasicToken : TokenBase
{ {
private string _username; private string _username;

View File

@ -9,12 +9,12 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A token constructed from a token from a bearer token. /// A token constructed from a token from a bearer token.
/// </summary> /// </summary>
public class BearerToken : TokenBase {{>visibility}} class BearerToken : TokenBase
{ {
private string _raw; private string _raw;

View File

@ -6,24 +6,17 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;{{#useCompareNetObjects}}
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}}
using Polly.Timeout;
using Polly.Extensions.Http;
using Polly;{{/supportsRetry}}
using {{packageName}}.Api;{{#useCompareNetObjects}}
using KellermanSoftware.CompareNetObjects;{{/useCompareNetObjects}} using KellermanSoftware.CompareNetObjects;{{/useCompareNetObjects}}
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Utility functions providing some benefit to API client consumers. /// Utility functions providing some benefit to API client consumers.
/// </summary> /// </summary>
public static class ClientUtils {{>visibility}} static class ClientUtils
{ {
{{#useCompareNetObjects}} {{#useCompareNetObjects}}
/// <summary> /// <summary>
@ -278,146 +271,5 @@ namespace {{packageName}}.Client
/// The format to use for DateTime serialization /// The format to use for DateTime serialization
/// </summary> /// </summary>
public const string ISO8601_DATETIME_FORMAT = "o"; public const string ISO8601_DATETIME_FORMAT = "o";
{{^hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
/// <param name="options"></param>
public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder)
{
builder.ConfigureServices((context, services) =>
{
HostConfiguration config = new HostConfiguration(services);
Add{{apiName}}(services, config);
});
return builder;
}
{{/hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
/// <param name="options"></param>
public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder, Action<HostBuilderContext, HostConfiguration> options)
{
builder.ConfigureServices((context, services) =>
{
HostConfiguration config = new HostConfiguration(services);
options(context, config);
Add{{apiName}}(services, config);
});
return builder;
}
{{^hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
public static void Add{{apiName}}(this IServiceCollection services)
{
HostConfiguration config = new HostConfiguration(services);
Add{{apiName}}(services, config);
}
{{/hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
public static void Add{{apiName}}(this IServiceCollection services, Action<HostConfiguration> 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}}
/// <summary>
/// Adds a Polly retry policy to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="retries"></param>
/// <returns></returns>
public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries)
{
client.AddPolicyHandler(RetryPolicy(retries));
return client;
}
/// <summary>
/// Adds a Polly timeout policy to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout)
{
client.AddPolicyHandler(TimeoutPolicy(timeout));
return client;
}
/// <summary>
/// Adds a Polly circiut breaker to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="handledEventsAllowedBeforeBreaking"></param>
/// <param name="durationOfBreak"></param>
/// <returns></returns>
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<HttpResponseMessage> RetryPolicy(int retries)
=> HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.RetryAsync(retries);
private static AsyncTimeoutPolicy<HttpResponseMessage> TimeoutPolicy(TimeSpan timeout)
=> Policy.TimeoutAsync<HttpResponseMessage>(timeout);
private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy<HttpResponseMessage> CircuitBreakerPolicy(
PolicyBuilder<HttpResponseMessage> builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak)
=> builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak);{{/supportsRetry}}
} }
} }

View File

@ -0,0 +1,22 @@
// <auto-generated>
{{partial_header}}
{{#nrt}}
#nullable enable
{{/nrt}}
using System.Linq;
using System.Collections.Generic;
namespace {{packageName}}.{{clientPackage}}
{
/// <summary>
/// A class containing a CookieContainer
/// </summary>
{{>visibility}} sealed class CookieContainer
{
/// <summary>
/// The collection of tokens
/// </summary>
public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer();
}
}

View File

@ -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",

View File

@ -4,14 +4,18 @@ using System.Globalization;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 /// 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 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types
/// </summary> /// </summary>
public class OpenAPIDateJsonConverter : JsonConverter<DateTime> {{>visibility}} class DateTimeJsonConverter : JsonConverter<DateTime>
{ {
public static readonly string[] FORMATS = {
{{>DateTimeFormats}}
};
/// <summary> /// <summary>
/// Returns a DateTime from the Json object /// Returns a DateTime from the Json object
/// </summary> /// </summary>
@ -19,8 +23,18 @@ namespace {{packageName}}.Client
/// <param name="typeToConvert"></param> /// <param name="typeToConvert"></param>
/// <param name="options"></param> /// <param name="options"></param>
/// <returns></returns> /// <returns></returns>
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
DateTime.ParseExact(reader.GetString(){{nrt!}}, "yyyy-MM-dd", CultureInfo.InvariantCulture); 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();
}
/// <summary> /// <summary>
/// Writes the DateTime to the json writer /// Writes the DateTime to the json writer
@ -29,6 +43,6 @@ namespace {{packageName}}.Client
/// <param name="dateTimeValue"></param> /// <param name="dateTimeValue"></param>
/// <param name="options"></param> /// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => 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));
} }
} }

View File

@ -0,0 +1,53 @@
{{>partial_header}}
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace {{packageName}}.{{clientPackage}}
{
/// <summary>
/// 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
/// </summary>
{{>visibility}} class DateTimeNullableJsonConverter : JsonConverter<DateTime?>
{
public static readonly string[] FORMATS = {
{{>DateTimeFormats}}
};
/// <summary>
/// Returns a DateTime from the Json object
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Writes the DateTime to the json writer
/// </summary>
/// <param name="writer"></param>
/// <param name="dateTimeValue"></param>
/// <param name="options"></param>
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));
}
}
}

View File

@ -0,0 +1 @@
{{#apiInfo}}{{#apis}}{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}

View File

@ -4,11 +4,12 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using {{packageName}}.Client; using {{packageName}}.{{clientPackage}};
using {{packageName}}.{{apiPackage}}; using {{packageName}}.{{interfacePrefix}}{{apiPackage}};
using {{packageName}}.Extensions;
using Xunit; using Xunit;
namespace {{packageName}}.Test.Api namespace {{packageName}}.Test.{{apiPackage}}
{ {
/// <summary> /// <summary>
/// Tests the dependency injection. /// Tests the dependency injection.
@ -16,7 +17,7 @@ namespace {{packageName}}.Test.Api
public class DependencyInjectionTest public class DependencyInjectionTest
{ {
private readonly IHost _hostUsingConfigureWithoutAClient = private readonly IHost _hostUsingConfigureWithoutAClient =
Host.CreateDefaultBuilder(Array.Empty<string>()).Configure{{apiName}}((context, options) => Host.CreateDefaultBuilder(Array.Empty<string>()).Configure{{apiName}}((context, services, options) =>
{ {
{{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1)); {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);
@ -37,7 +38,7 @@ namespace {{packageName}}.Test.Api
.Build(); .Build();
private readonly IHost _hostUsingConfigureWithAClient = private readonly IHost _hostUsingConfigureWithAClient =
Host.CreateDefaultBuilder(Array.Empty<string>()).Configure{{apiName}}((context, options) => Host.CreateDefaultBuilder(Array.Empty<string>()).Configure{{apiName}}((context, services, options) =>
{ {
{{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1)); {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);
@ -113,7 +114,7 @@ namespace {{packageName}}.Test.Api
[Fact] [Fact]
public void ConfigureApiWithAClientTest() 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}} Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}}
{{/-last}}{{/apis}}{{/apiInfo}} {{/-last}}{{/apis}}{{/apiInfo}}
@ -125,7 +126,7 @@ namespace {{packageName}}.Test.Api
[Fact] [Fact]
public void ConfigureApiWithoutAClientTest() 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}} Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}}
{{/-last}}{{/apis}}{{/apiInfo}} {{/-last}}{{/apis}}{{/apiInfo}}
@ -137,7 +138,7 @@ namespace {{packageName}}.Test.Api
[Fact] [Fact]
public void AddApiWithAClientTest() 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}} Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}}
{{/-last}}{{/apis}}{{/apiInfo}} {{/-last}}{{/apis}}{{/apiInfo}}
@ -149,7 +150,7 @@ namespace {{packageName}}.Test.Api
[Fact] [Fact]
public void AddApiWithoutAClientTest() 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}} Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}}
{{/-last}}{{/apis}}{{/apiInfo}} {{/-last}}{{/apis}}{{/apiInfo}}

View File

@ -10,18 +10,22 @@ using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Net.Http; using System.Net.Http;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using {{packageName}}.Api; using {{packageName}}.{{modelPackage}};
using {{packageName}}.Model;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Provides hosting configuration for {{packageName}} /// Provides hosting configuration for {{packageName}}
/// </summary> /// </summary>
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 readonly IServiceCollection _services;
private JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions();
internal bool HttpClientsAdded { get; private set; } internal bool HttpClientsAdded { get; private set; }
@ -33,30 +37,22 @@ namespace {{packageName}}.Client
{ {
_services = services; _services = services;
_jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new JsonStringEnumConverter());
_jsonOptions.Converters.Add(new OpenAPIDateJsonConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter());
{{#models}} _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter());
{{#model}} {{#models}}
{{^isEnum}} {{#model}}
{{#allOf}} {{#isEnum}}
{{#-first}} _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()); _jsonOptions.Converters.Add(new {{classname}}JsonConverter());
{{/-first}} {{/isEnum}}
{{/allOf}} {{/model}}
{{#anyOf}} {{/models}}
{{#-first}} _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions));
_jsonOptions.Converters.Add(new {{classname}}JsonConverter()); _services.AddSingleton<IApiFactory, ApiFactory>();{{#apiInfo}}{{#apis}}
{{/-first}} _services.AddTransient<T{{classname}}, T{{classname}}>();{{/apis}}{{/apiInfo}}
{{/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}}
} }
/// <summary> /// <summary>
@ -65,17 +61,16 @@ namespace {{packageName}}.Client
/// <param name="client"></param> /// <param name="client"></param>
/// <param name="builder"></param> /// <param name="builder"></param>
/// <returns></returns> /// <returns></returns>
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<HttpClient>{{nrt?}} client = null, Action<IHttpClientBuilder>{{nrt?}} builder = null){{#apis}} Action<HttpClient>{{nrt?}} client = null, Action<IHttpClientBuilder>{{nrt?}} builder = null)
where T{{classname}} : class, {{interfacePrefix}}{{classname}}{{/apis}}
{ {
if (client == null) if (client == null)
client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS);
List<IHttpClientBuilder> builders = new List<IHttpClientBuilder>(); List<IHttpClientBuilder> builders = new List<IHttpClientBuilder>();
{{#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}} {{/apis}}{{/apiInfo}}
if (builder != null) if (builder != null)
foreach (IHttpClientBuilder instance in builders) foreach (IHttpClientBuilder instance in builders)
@ -86,25 +81,12 @@ namespace {{packageName}}.Client
return this; return this;
} }
/// <summary>
/// Configures the HttpClients.
/// </summary>
/// <param name="client"></param>
/// <param name="builder"></param>
/// <returns></returns>
public HostConfiguration Add{{apiName}}HttpClients(Action<HttpClient>{{nrt?}} client = null, Action<IHttpClientBuilder>{{nrt?}} builder = null)
{
Add{{apiName}}HttpClients<{{#apiInfo}}{{#apis}}{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(client, builder);
return this;
}
/// <summary> /// <summary>
/// Configures the JsonSerializerSettings /// Configures the JsonSerializerSettings
/// </summary> /// </summary>
/// <param name="options"></param> /// <param name="options"></param>
/// <returns></returns> /// <returns></returns>
public HostConfiguration ConfigureJsonOptions(Action<JsonSerializerOptions> options) public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> ConfigureJsonOptions(Action<JsonSerializerOptions> options)
{ {
options(_jsonOptions); options(_jsonOptions);
@ -117,7 +99,7 @@ namespace {{packageName}}.Client
/// <typeparam name="TTokenBase"></typeparam> /// <typeparam name="TTokenBase"></typeparam>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public HostConfiguration AddTokens<TTokenBase>(TTokenBase token) where TTokenBase : TokenBase public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> AddTokens<TTokenBase>(TTokenBase token) where TTokenBase : TokenBase
{ {
return AddTokens(new TTokenBase[]{ token }); return AddTokens(new TTokenBase[]{ token });
} }
@ -128,7 +110,7 @@ namespace {{packageName}}.Client
/// <typeparam name="TTokenBase"></typeparam> /// <typeparam name="TTokenBase"></typeparam>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <returns></returns> /// <returns></returns>
public HostConfiguration AddTokens<TTokenBase>(IEnumerable<TTokenBase> tokens) where TTokenBase : TokenBase public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> AddTokens<TTokenBase>(IEnumerable<TTokenBase> tokens) where TTokenBase : TokenBase
{ {
TokenContainer<TTokenBase> container = new TokenContainer<TTokenBase>(tokens); TokenContainer<TTokenBase> container = new TokenContainer<TTokenBase>(tokens);
_services.AddSingleton(services => container); _services.AddSingleton(services => container);
@ -142,7 +124,7 @@ namespace {{packageName}}.Client
/// <typeparam name="TTokenProvider"></typeparam> /// <typeparam name="TTokenProvider"></typeparam>
/// <typeparam name="TTokenBase"></typeparam> /// <typeparam name="TTokenBase"></typeparam>
/// <returns></returns> /// <returns></returns>
public HostConfiguration UseProvider<TTokenProvider, TTokenBase>() public HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}> UseProvider<TTokenProvider, TTokenBase>()
where TTokenProvider : TokenProvider<TTokenBase> where TTokenProvider : TokenProvider<TTokenBase>
where TTokenBase : TokenBase where TTokenBase : TokenBase
{ {

View File

@ -13,12 +13,12 @@ using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Web; using System.Web;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Class for HttpSigning auth related parameter and methods /// Class for HttpSigning auth related parameter and methods
/// </summary> /// </summary>
public class HttpSigningConfiguration {{>visibility}} class HttpSigningConfiguration
{ {
#region #region
/// <summary> /// <summary>

View File

@ -9,12 +9,12 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A token constructed from an HttpSigningConfiguration /// A token constructed from an HttpSigningConfiguration
/// </summary> /// </summary>
public class HttpSignatureToken : TokenBase {{>visibility}} class HttpSignatureToken : TokenBase
{ {
private HttpSigningConfiguration _configuration; private HttpSigningConfiguration _configuration;

View File

@ -1,21 +1,15 @@
using System.Net.Http; using System.Net.Http;
namespace {{packageName}}.Client namespace {{packageName}}.{{interfacePrefix}}{{apiPackage}}
{ {
/// <summary> /// <summary>
/// Any Api client /// Any Api client
/// </summary> /// </summary>
public interface {{interfacePrefix}}Api {{>visibility}} interface {{interfacePrefix}}Api
{ {
/// <summary> /// <summary>
/// The HttpClient /// The HttpClient
/// </summary> /// </summary>
HttpClient HttpClient { get; } HttpClient HttpClient { get; }
/// <summary>
/// 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.
/// </summary>
event ClientUtils.EventHandler<ApiResponseEventArgs>{{nrt?}} ApiResponded;
} }
} }

View File

@ -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
{
/// <summary>
/// Extension methods for IHostBuilder
/// </summary>
{{>visibility}} static class IHostBuilderExtensions
{
{{^hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
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;
}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder)
=> Configure{{apiName}}<{{>DefaultApis}}>(builder);
{{/hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
/// <param name="options"></param>
public static IHostBuilder Configure{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IHostBuilder builder, Action<HostBuilderContext, IServiceCollection, HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>> 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;
}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="builder"></param>
/// <param name="options"></param>
public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder, Action<HostBuilderContext, IServiceCollection, HostConfiguration<{{>DefaultApis}}>> options)
=> Configure{{apiName}}<{{>DefaultApis}}>(builder, options);
}
}

View File

@ -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
{
/// <summary>
/// Extension methods for IHttpClientBuilder
/// </summary>
{{>visibility}} static class IHttpClientBuilderExtensions
{
{{#supportsRetry}}
/// <summary>
/// Adds a Polly retry policy to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="retries"></param>
/// <returns></returns>
public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries)
{
client.AddPolicyHandler(RetryPolicy(retries));
return client;
}
/// <summary>
/// Adds a Polly timeout policy to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout)
{
client.AddPolicyHandler(TimeoutPolicy(timeout));
return client;
}
/// <summary>
/// Adds a Polly circiut breaker to your clients.
/// </summary>
/// <param name="client"></param>
/// <param name="handledEventsAllowedBeforeBreaking"></param>
/// <param name="durationOfBreak"></param>
/// <returns></returns>
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<HttpResponseMessage> RetryPolicy(int retries)
=> HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.RetryAsync(retries);
private static AsyncTimeoutPolicy<HttpResponseMessage> TimeoutPolicy(TimeSpan timeout)
=> Policy.TimeoutAsync<HttpResponseMessage>(timeout);
private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy<HttpResponseMessage> CircuitBreakerPolicy(
PolicyBuilder<HttpResponseMessage> builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak)
=> builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak);
{{/supportsRetry}}
}
}

View File

@ -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
{
/// <summary>
/// Extension methods for IServiceCollection
/// </summary>
{{>visibility}} static class IServiceCollectionExtensions
{
{{^hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
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);
}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
public static void Add{{apiName}}(this IServiceCollection services)
{
HostConfiguration<{{>DefaultApis}}> config = new HostConfiguration<{{>DefaultApis}}>(services);
Add{{apiName}}(services, config);
}
{{/hasAuthMethods}}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
public static void Add{{apiName}}<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>(this IServiceCollection services, Action<HostConfiguration<{{#apiInfo}}{{#apis}}T{{classname}}{{^-last}}, {{/-last}}{{/apis}}{{/apiInfo}}>> 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);
}
/// <summary>
/// Add the api to your host builder.
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
public static void Add{{apiName}}(this IServiceCollection services, Action<HostConfiguration<{{>DefaultApis}}>> 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<CookieContainer>();
// 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)));
}
}
}
}
}

View File

@ -0,0 +1,3 @@
{{#readOnlyVars}}
{{#-first}}
{{#parent}}, {{/parent}}{{^parent}} : {{/parent}}IEquatable<{{classname}}{{nrt?}}>{{/-first}}{{/readOnlyVars}}

View File

@ -0,0 +1,4 @@
{{#validatable}}
{{^parent}}
{{^readOnlyVars}}
: {{/readOnlyVars}}{{/parent}}{{#parent}}{{^readOnlyVars}}, {{/readOnlyVars}}{{/parent}}{{^parent}}{{#readOnlyVars}}{{#-first}}, {{/-first}}{{/readOnlyVars}}{{/parent}}IValidatableObject{{/validatable}}

View File

@ -1,15 +1,8 @@
/// <summary> /// <summary>
/// A Json converter for type {{classname}} /// A Json converter for type {{classname}}
/// </summary> /// </summary>
public class {{classname}}JsonConverter : JsonConverter<{{classname}}> {{>visibility}} class {{classname}}JsonConverter : JsonConverter<{{classname}}>
{ {
/// <summary>
/// Returns a boolean if the type is compatible with this converter.
/// </summary>
/// <param name="typeToConvert"></param>
/// <returns></returns>
public override bool CanConvert(Type typeToConvert) => typeof({{classname}}).IsAssignableFrom(typeToConvert);
/// <summary> /// <summary>
/// A Json reader. /// A Json reader.
/// </summary> /// </summary>
@ -22,9 +15,11 @@
{ {
int currentDepth = reader.CurrentDepth; int currentDepth = reader.CurrentDepth;
if (reader.TokenType != JsonTokenType.StartObject) if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray)
throw new JsonException(); throw new JsonException();
JsonTokenType startingTokenType = reader.TokenType;
{{#composedSchemas.anyOf}} {{#composedSchemas.anyOf}}
Utf8JsonReader {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader = reader; 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 {{#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}} {{#composedSchemas.allOf}}
{{^isInherited}} {{^isInherited}}
Utf8JsonReader {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}Reader = reader; 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}} {{/isInherited}}
{{/composedSchemas.allOf}} {{/composedSchemas.allOf}}
{{#allVars}} {{#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}} {{/allVars}}
while (reader.Read()) while (reader.Read())
{ {
if (reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth)
break; 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(); string{{nrt?}} propertyName = reader.GetString();
reader.Read(); reader.Read();
@ -61,48 +59,92 @@
{{#allVars}} {{#allVars}}
case "{{baseName}}": case "{{baseName}}":
{{#isString}} {{#isString}}
{{^isMap}}
{{^isEnum}}
{{^isUuid}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetString(); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetString();
{{/isUuid}}
{{/isEnum}}
{{/isMap}}
{{/isString}} {{/isString}}
{{#isBoolean}} {{#isBoolean}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetBoolean(); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetBoolean();
{{/isBoolean}} {{/isBoolean}}
{{#isDecimal}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDecimal();
{{/isDecimal}}
{{#isNumeric}} {{#isNumeric}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt32(); {{^isEnum}}
{{/isNumeric}}
{{#isLong}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetInt64();
{{/isLong}}
{{#isDouble}} {{#isDouble}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDouble(); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDouble();
{{/isDouble}} {{/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}} {{#isDate}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDateTime(); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<DateTime{{#isNullable}}?{{/isNullable}}>(ref reader, options);
{{/isDate}} {{/isDate}}
{{#isDateTime}} {{#isDateTime}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = reader.GetDateTime(); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<DateTime{{#isNullable}}?{{/isNullable}}>(ref reader, options);
{{/isDateTime}} {{/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}} {{^isString}}
{{^isBoolean}} {{^isBoolean}}
{{^isDecimal}}
{{^isNumeric}} {{^isNumeric}}
{{^isLong}}
{{^isDouble}}
{{^isDate}} {{^isDate}}
{{^isDateTime}} {{^isDateTime}}
{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref reader, options); {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref reader, options);
{{/isDateTime}} {{/isDateTime}}
{{/isDate}} {{/isDate}}
{{/isDouble}}
{{/isLong}}
{{/isNumeric}} {{/isNumeric}}
{{/isDecimal}}
{{/isBoolean}} {{/isBoolean}}
{{/isString}} {{/isString}}
{{/isEnum}}
{{/isUuid}}
break; break;
{{/allVars}} {{/allVars}}
default:
break;
} }
} }
} }
@ -127,5 +169,95 @@
/// <param name="{{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}"></param> /// <param name="{{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}"></param>
/// <param name="options"></param> /// <param name="options"></param>
/// <exception cref="NotImplementedException"></exception> /// <exception cref="NotImplementedException"></exception>
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();
}
} }

View File

@ -6,12 +6,12 @@
{{/nrt}} {{/nrt}}
using System.Text.Json; using System.Text.Json;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// Provides the JsonSerializerOptions /// Provides the JsonSerializerOptions
/// </summary> /// </summary>
public class JsonSerializerOptionsProvider {{>visibility}} class JsonSerializerOptionsProvider
{ {
/// <summary> /// <summary>
/// the JsonSerializerOptions /// the JsonSerializerOptions

View File

@ -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}}

View File

@ -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}}

View File

@ -9,12 +9,12 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A token constructed with OAuth. /// A token constructed with OAuth.
/// </summary> /// </summary>
public class OAuthToken : TokenBase {{>visibility}} class OAuthToken : TokenBase
{ {
private string _raw; private string _raw;

View File

@ -0,0 +1,24 @@
/// <summary>
/// {{summary}} {{notes}}
/// </summary>
/// <exception cref="ApiException">Thrown when fails to make API call</exception>
{{#allParams}}
/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>
{{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns><see cref="Task"/>&lt;<see cref="{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}"/>&gt;</returns>
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;
}

View File

@ -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}}

View File

@ -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}}

View File

@ -102,6 +102,9 @@ namespace YourProject
It depends how you made the request. If the return type is ApiResponse<T> no error will be thrown, though the Content property will be null. It depends how you made the request. If the return type is ApiResponse<T> no error will be thrown, though the Content property will be null.
StatusCode and ReasonPhrase will contain information about the error. 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. 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.
<a name="dependencies"></a> <a name="dependencies"></a>
## Dependencies ## 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.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](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 - [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}} - [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later{{/supportsRetry}}{{#useCompareNetObjects}}
- [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}}
- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later{{/useCompareNetObjects}}{{#validatable}} - [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}} - [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later{{/validatable}}{{#apiDocs}}

View File

@ -0,0 +1 @@
# Created with Openapi Generator

View File

@ -11,13 +11,13 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks;{{/netStandard}} using System.Threading.Tasks;{{/netStandard}}
namespace {{packageName}}.Client {{^netStandard}} namespace {{packageName}}.{{clientPackage}} {{^netStandard}}
{ {
/// <summary> /// <summary>
/// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan.
/// </summary> /// </summary>
/// <typeparam name="TTokenBase"></typeparam> /// <typeparam name="TTokenBase"></typeparam>
public class RateLimitProvider<TTokenBase> : TokenProvider<TTokenBase> where TTokenBase : TokenBase {{>visibility}} class RateLimitProvider<TTokenBase> : TokenProvider<TTokenBase> where TTokenBase : TokenBase
{ {
internal Channel<TTokenBase> AvailableTokens { get; } internal Channel<TTokenBase> AvailableTokens { get; }

View File

@ -6,12 +6,12 @@
{{/nrt}} {{/nrt}}
using System; using System;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// The base for all tokens. /// The base for all tokens.
/// </summary> /// </summary>
public abstract class TokenBase {{>visibility}} abstract class TokenBase
{ {
private DateTime _nextAvailable = DateTime.UtcNow; private DateTime _nextAvailable = DateTime.UtcNow;
private object _nextAvailableLock = new object(); private object _nextAvailableLock = new object();

View File

@ -7,13 +7,13 @@
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
namespace {{packageName}}.Client namespace {{packageName}}.{{clientPackage}}
{ {
/// <summary> /// <summary>
/// A container for a collection of tokens. /// A container for a collection of tokens.
/// </summary> /// </summary>
/// <typeparam name="TTokenBase"></typeparam> /// <typeparam name="TTokenBase"></typeparam>
public sealed class TokenContainer<TTokenBase> where TTokenBase : TokenBase {{>visibility}} sealed class TokenContainer<TTokenBase> where TTokenBase : TokenBase
{ {
/// <summary> /// <summary>
/// The collection of tokens /// The collection of tokens

View File

@ -7,14 +7,14 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using {{packageName}}.Client; using {{packageName}}.{{clientPackage}};
namespace {{packageName}} namespace {{packageName}}
{ {
/// <summary> /// <summary>
/// A class which will provide tokens. /// A class which will provide tokens.
/// </summary> /// </summary>
public abstract class TokenProvider<TTokenBase> where TTokenBase : TokenBase {{>visibility}} abstract class TokenProvider<TTokenBase> where TTokenBase : TokenBase
{ {
/// <summary> /// <summary>
/// The array of tokens. /// The array of tokens.

View File

@ -12,16 +12,17 @@ using Microsoft.Extensions.Logging;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text.Json; using System.Text.Json;
using {{packageName}}.Client; using {{packageName}}.{{clientPackage}};
{{#hasImport}} {{#hasImport}}
using {{packageName}}.{{modelPackage}}; using {{packageName}}.{{modelPackage}};
{{/hasImport}} {{/hasImport}}
namespace {{packageName}}.{{apiPackage}} namespace {{packageName}}.{{interfacePrefix}}{{apiPackage}}
{ {
{{#operations}} {{#operations}}
/// <summary> /// <summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// This class is registered as transient.
/// </summary> /// </summary>
{{>visibility}} interface {{interfacePrefix}}{{classname}} : IApi {{>visibility}} interface {{interfacePrefix}}{{classname}} : IApi
{ {
@ -38,7 +39,7 @@ namespace {{packageName}}.{{apiPackage}}
{{/allParams}} {{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task&lt;ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}&gt;&gt;</returns> /// <returns>Task&lt;ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}&gt;&gt;</returns>
Task<ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>> {{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<ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>> {{operationId}}WithHttpInfoAsync({{>OperationSignature}});
/// <summary> /// <summary>
/// {{summary}} /// {{summary}}
@ -52,7 +53,7 @@ namespace {{packageName}}.{{apiPackage}}
{{/allParams}} {{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}&gt;</returns> /// <returns>Task of ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}&gt;</returns>
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> /// <summary>
/// {{summary}} /// {{summary}}
@ -65,26 +66,23 @@ namespace {{packageName}}.{{apiPackage}}
{{/allParams}} {{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}?&gt;</returns> /// <returns>Task of ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}?&gt;</returns>
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}} {{/-last}}
{{/operation}} {{/operation}}
} }
}
namespace {{packageName}}.{{apiPackage}}
{
/// <summary> /// <summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// </summary> /// </summary>
{{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}
{ {
private JsonSerializerOptions _jsonSerializerOptions; private JsonSerializerOptions _jsonSerializerOptions;
/// <summary>
/// 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.
/// </summary>
public event ClientUtils.EventHandler<ApiResponseEventArgs>{{nrt?}} ApiResponded;
/// <summary> /// <summary>
/// The logger /// The logger
/// </summary> /// </summary>
@ -140,6 +138,15 @@ namespace {{packageName}}.{{apiPackage}}
HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}
OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}} OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}}
} }
/// <summary>
/// Logs the api response
/// </summary>
/// <param name="args"></param>
protected virtual void OnApiResponded(ApiResponseEventArgs args)
{
Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path);
}
{{#operation}} {{#operation}}
/// <summary> /// <summary>
@ -151,7 +158,7 @@ namespace {{packageName}}.{{apiPackage}}
{{/allParams}} {{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns><see cref="Task"/>&lt;<see cref="{{#returnType}}{{.}}{{/returnType}}{{^returnType}}object{{/returnType}}"/>&gt;</returns> /// <returns><see cref="Task"/>&lt;<see cref="{{#returnType}}{{.}}{{/returnType}}{{^returnType}}object{{/returnType}}"/>&gt;</returns>
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); 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}} #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); 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}} {{#nrt}}
/// <summary> {{>OperationOrDefault}}
/// {{summary}} {{notes}}
/// </summary>
/// <exception cref="ApiException">Thrown when fails to make API call</exception>
{{#allParams}}
/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>
{{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns><see cref="Task"/>&lt;<see cref="{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}"/>&gt;</returns>
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;
}
{{/nrt}} {{/nrt}}
{{^nrt}} {{^nrt}}
{{^returnTypeIsPrimitive}} {{^returnTypeIsPrimitive}}
{{! Note that this method is a copy paste of above due to NRT complexities }} {{>OperationOrDefault}}
/// <summary>
/// {{summary}} {{notes}}
/// </summary>
/// <exception cref="ApiException">Thrown when fails to make API call</exception>
{{#allParams}}
/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>
{{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns><see cref="Task"/>&lt;<see cref="{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}"/>&gt;</returns>
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;
}
{{/returnTypeIsPrimitive}} {{/returnTypeIsPrimitive}}
{{/nrt}} {{/nrt}}
/// <summary>
/// Validates the request parameters
/// </summary>
{{#allParams}}
/// <param name="{{paramName}}"></param>
{{/allParams}}
/// <returns></returns>
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}};
}
/// <summary>
/// Processes the server response
/// </summary>
/// <param name="apiResponse"></param>
{{#allParams}}
/// <param name="{{paramName}}"></param>
{{/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}})
{
}
/// <summary>
/// Processes the server response
/// </summary>
/// <param name="exception"></param>
/// <param name="pathFormat"></param>
/// <param name="path"></param>
{{#allParams}}
/// <param name="{{paramName}}"></param>
{{/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> /// <summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> /// </summary>
@ -229,33 +250,53 @@ namespace {{packageName}}.{{apiPackage}}
{{/allParams}} {{/allParams}}
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns><see cref="Task"/>&lt;<see cref="ApiResponse{T}"/>&gt; where T : <see cref="{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}"/></returns> /// <returns><see cref="Task"/>&lt;<see cref="ApiResponse{T}"/>&gt; where T : <see cref="{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}object{{/returnType}}"/></returns>
public async Task<ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>> {{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<ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>> {{operationId}}WithHttpInfoAsync({{>OperationSignature}})
{ {
UriBuilder uriBuilder = new UriBuilder();
try 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) using (HttpRequestMessage request = new HttpRequestMessage())
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())
{ {
UriBuilder uriBuilder = new UriBuilder(); {{^servers}}
uriBuilder.Host = HttpClient.BaseAddress{{nrt!}}.Host; uriBuilder.Host = HttpClient.BaseAddress{{nrt!}}.Host;
uriBuilder.Port = HttpClient.BaseAddress{{nrt!}}.Port; uriBuilder.Port = HttpClient.BaseAddress{{nrt!}}.Port;
uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Scheme = ClientUtils.SCHEME;
uriBuilder.Path = ClientUtils.CONTEXT_PATH + "{{path}}";{{#pathParams}}{{#required}} uriBuilder.Path = ClientUtils.CONTEXT_PATH + "{{path}}";
uriBuilder.Path = uriBuilder.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString()));{{/required}}{{^required}}
{{/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) if ({{paramName}} != null)
uriBuilder.Path = uriBuilder.Path + $"/{ Uri.EscapeDataString({{paramName}}).ToString()) }"; 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);{{/-first}}{{/queryParams}}{{^queryParams}}{{#authMethods}}{{#isApiKey}}{{#isKeyInQuery}}
System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty);{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}}{{/queryParams}}{{#queryParams}}{{#required}}{{#-first}} 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) {{/-first}}{{/queryParams}}{{#queryParams}}{{^required}}if ({{paramName}} != null)
parseQueryString["{{baseName}}"] = Uri.EscapeDataString({{paramName}}.ToString(){{nrt!}}); 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) 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(); MultipartContent multipartContent = new MultipartContent();
request.Content = multipartContent; request.Content = multipartContent;
@ -281,22 +332,39 @@ namespace {{packageName}}.{{apiPackage}}
multipartContent.Add(new FormUrlEncodedContent(formParams));{{/-first}}{{^isFile}}{{#required}} multipartContent.Add(new FormUrlEncodedContent(formParams));{{/-first}}{{^isFile}}{{#required}}
formParams.Add(new KeyValuePair<string{{nrt?}}, string{{nrt?}}>("{{baseName}}", ClientUtils.ParameterToString({{paramName}})));{{/required}}{{^required}} formParams.Add(new KeyValuePair<string{{nrt?}}, string{{nrt?}}>("{{baseName}}", ClientUtils.ParameterToString({{paramName}})));
{{/required}}
{{^required}}
if ({{paramName}} != null) if ({{paramName}} != null)
formParams.Add(new KeyValuePair<string{{nrt?}}, string{{nrt?}}>("{{baseName}}", ClientUtils.ParameterToString({{paramName}})));{{/required}}{{/isFile}}{{#isFile}}{{#required}} formParams.Add(new KeyValuePair<string{{nrt?}}, string{{nrt?}}>("{{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) 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 = ({{paramName}} as object) is System.IO.Stream stream
? request.Content = new StreamContent(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<TokenBase> tokens = new List<TokenBase>();{{/-first}}{{#isApiKey}} {{/bodyParam}}
{{#authMethods}}
{{#-first}}
List<TokenBase> tokens = new List<TokenBase>();
{{/-first}}
{{#isApiKey}}
ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); ApiKeyToken apiKey = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false);
tokens.Add(apiKey);{{#isKeyInHeader}} tokens.Add(apiKey);{{#isKeyInHeader}}
@ -305,11 +373,7 @@ namespace {{packageName}}.{{apiPackage}}
apiKey.UseInQuery(request, uriBuilder, parseQueryString, "{{keyParamName}}"); apiKey.UseInQuery(request, uriBuilder, parseQueryString, "{{keyParamName}}");
uriBuilder.Query = parseQueryString.ToString();{{/isKeyInQuery}}{{#isKeyInCookie}} uriBuilder.Query = parseQueryString.ToString();{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}}
apiKey.UseInCookie(request, parseQueryString, "{{keyParamName}}");
uriBuilder.Query = parseQueryString.ToString();{{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}}
{{! below line must be after any UseInQuery calls, but before using the HttpSignatureToken}} {{! below line must be after any UseInQuery calls, but before using the HttpSignatureToken}}
request.RequestUri = uriBuilder.Uri;{{#authMethods}}{{#isBasicBasic}} request.RequestUri = uriBuilder.Uri;{{#authMethods}}{{#isBasicBasic}}
@ -348,7 +412,7 @@ namespace {{packageName}}.{{apiPackage}}
string{{nrt?}} contentType = ClientUtils.SelectHeaderContentType(contentTypes); string{{nrt?}} contentType = ClientUtils.SelectHeaderContentType(contentTypes);
if (contentType != null) 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}} string[] accepts = new string[] { {{/-first}}{{/produces}}
{{#produces}}"{{{mediaType}}}"{{^-last}}, {{#produces}}"{{{mediaType}}}"{{^-last}},
@ -359,35 +423,33 @@ namespace {{packageName}}.{{apiPackage}}
if (accept != null) if (accept != null)
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); 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 = 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 }} 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)) 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); 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); ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}> apiResponse = new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}}>(responseMessage, responseContent);
if (apiResponse.IsSuccessStatusCode) 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) else if (apiResponse.StatusCode == (HttpStatusCode) 429)
foreach(TokenBase token in tokens) foreach(TokenBase token in tokens)
token.BeginRateLimit();{{/authMethods}} token.BeginRateLimit();
{{/authMethods}}
return apiResponse; return apiResponse;
} }
@ -395,11 +457,10 @@ namespace {{packageName}}.{{apiPackage}}
} }
catch(Exception e) 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; throw;
} }
}{{^-last}} }
{{/-last}}
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -4,25 +4,25 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using {{packageName}}.{{apiPackage}};{{#hasImport}} using {{packageName}}.{{interfacePrefix}}{{apiPackage}};{{#hasImport}}
using {{packageName}}.{{modelPackage}};{{/hasImport}} using {{packageName}}.{{modelPackage}};{{/hasImport}}
{{{testInstructions}}} {{>testInstructions}}
namespace {{packageName}}.Test.Api namespace {{packageName}}.Test.{{apiPackage}}
{ {
/// <summary> /// <summary>
/// Class for testing {{classname}} /// Class for testing {{classname}}
/// </summary> /// </summary>
public sealed class {{classname}}Tests : ApiTestsBase public sealed class {{classname}}Tests : ApiTestsBase
{ {
private readonly {{interfacePrefix}}{{classname}} _instance; private readonly {{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}} _instance;
public {{classname}}Tests(): base(Array.Empty<string>()) public {{classname}}Tests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); _instance = _host.Services.GetRequiredService<{{interfacePrefix}}{{apiPackage}}.{{interfacePrefix}}{{classname}}>();
} }
{{#operations}} {{#operations}}

View File

@ -10,7 +10,9 @@ using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.IO; using System.IO;
{{^useGenericHost}}
using System.Runtime.Serialization; using System.Runtime.Serialization;
{{/useGenericHost}}
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Text.Json; using System.Text.Json;
@ -26,23 +28,13 @@ using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils;
namespace {{packageName}}.{{modelPackage}} namespace {{packageName}}.{{modelPackage}}
{ {
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>modelGeneric}} {{#isEnum}}
{{>modelEnum}}
{{/isEnum}}
{{^isEnum}}
{{>modelGeneric}}
{{#allOf}}
{{#-first}}
{{>JsonConverter}} {{>JsonConverter}}
{{/-first}}
{{/allOf}}
{{#anyOf}}
{{#-first}}
{{>JsonConverter}}
{{/-first}}
{{/anyOf}}
{{#oneOf}}
{{#-first}}
{{>JsonConverter}}
{{/-first}}
{{/oneOf}}
{{/isEnum}} {{/isEnum}}
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -1,7 +1,7 @@
/// <summary> /// <summary>
/// {{description}}{{^description}}{{classname}}{{/description}} /// {{description}}{{^description}}{{classname}}{{/description}}
/// </summary> /// </summary>
{{>visibility}} partial class {{classname}} : {{#parent}}{{{.}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}{{^parentModel}}, IValidatableObject{{/parentModel}}{{/validatable}} {{>visibility}} partial class {{classname}}{{#parent}} : {{{.}}}{{/parent}}{{>ImplementsIEquatable}}{{>ImplementsValidatable}}
{ {
{{#composedSchemas.oneOf}} {{#composedSchemas.oneOf}}
/// <summary> /// <summary>
@ -17,21 +17,26 @@
/// <param name="{{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}{{#isNullable}}{{nrt?}}{{/isNullable}}"></param> /// <param name="{{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}{{#isNullable}}{{nrt?}}{{/isNullable}}"></param>
{{/composedSchemas.anyOf}} {{/composedSchemas.anyOf}}
{{#allVars}} {{#allVars}}
/// <param name="{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}">{{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}</param> /// <param name="{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}">{{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}</param>
{{/allVars}} {{/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}} {{#nonNullableVars}}
{{^isInherited}} {{#-first}}
{{#required}} #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
{{^isNullable}} #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null'
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}} {{/-first}}
{{/required}} if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} == null)
{{/isInherited}} throw new ArgumentNullException(nameof({{name}}));
{{/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}}
{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}};
{{#composedSchemas.allOf}} {{#composedSchemas.allOf}}
{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}};
@ -60,21 +65,26 @@
/// <param name="{{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}{{#isNullable}}{{nrt?}}{{/isNullable}}"></param> /// <param name="{{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}{{#isNullable}}{{nrt?}}{{/isNullable}}"></param>
{{/composedSchemas.anyOf}} {{/composedSchemas.anyOf}}
{{#allVars}} {{#allVars}}
/// <param name="{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}">{{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}</param> /// <param name="{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}">{{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}</param>
{{/allVars}} {{/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}} {{#nonNullableVars}}
{{^isInherited}} {{#-first}}
{{#required}} #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
{{^isNullable}} #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) 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."); throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null.");
{{/isNullable}} {{#-last}}
{{/required}} #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
{{/isInherited}} #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null'
{{/allVars}}
{{/-last}}
{{/nonNullableVars}}
{{#composedSchemas.allOf}} {{#composedSchemas.allOf}}
{{^isInherited}} {{^isInherited}}
{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}}; {{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.camelcase_param}};
@ -115,7 +125,7 @@
{{#deprecated}} {{#deprecated}}
[Obsolete] [Obsolete]
{{/deprecated}} {{/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}} {{/isEnum}}
{{/vars}} {{/vars}}
@ -127,7 +137,7 @@
{{#deprecated}} {{#deprecated}}
[Obsolete] [Obsolete]
{{/deprecated}} {{/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.anyOf}}
{{#composedSchemas.oneOf}} {{#composedSchemas.oneOf}}
@ -138,7 +148,7 @@
{{#deprecated}} {{#deprecated}}
[Obsolete] [Obsolete]
{{/deprecated}} {{/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.oneOf}}
{{#composedSchemas.allOf}} {{#composedSchemas.allOf}}
@ -150,7 +160,7 @@
{{#deprecated}} {{#deprecated}}
[Obsolete] [Obsolete]
{{/deprecated}} {{/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}} {{/isInherited}}
{{/composedSchemas.allOf}} {{/composedSchemas.allOf}}
@ -165,7 +175,7 @@
{{#deprecated}} {{#deprecated}}
[Obsolete] [Obsolete]
{{/deprecated}} {{/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}} {{/isEnum}}
{{/isInherited}} {{/isInherited}}
@ -176,7 +186,7 @@
/// Gets or Sets additional properties /// Gets or Sets additional properties
/// </summary> /// </summary>
[JsonExtensionData] [JsonExtensionData]
public Dictionary<string, JsonElement> AdditionalProperties { get; set; } = new Dictionary<string, JsonElement>(); public Dictionary<string, JsonElement> AdditionalProperties { get; } = new Dictionary<string, JsonElement>();
{{/parentModel}} {{/parentModel}}
{{/isAdditionalPropertiesTrue}} {{/isAdditionalPropertiesTrue}}
@ -202,6 +212,8 @@
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
{{#readOnlyVars}}
{{#-first}}
/// <summary> /// <summary>
/// Returns true if objects are equal /// Returns true if objects are equal
@ -230,29 +242,28 @@
{{/useCompareNetObjects}} {{/useCompareNetObjects}}
{{^useCompareNetObjects}} {{^useCompareNetObjects}}
if (input == null) if (input == null)
{
return false; 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}} {{^vendorExtensions.x-is-value-type}}
(this.{{name}} != null && ({{name}} != null &&
this.{{name}}.Equals(input.{{name}})) {{name}}.Equals(input.{{name}}))
{{/vendorExtensions.x-is-value-type}} {{/vendorExtensions.x-is-value-type}}
{{#vendorExtensions.x-is-value-type}} {{#vendorExtensions.x-is-value-type}}
this.{{name}}.Equals(input.{{name}}) {{name}}.Equals(input.{{name}})
{{/vendorExtensions.x-is-value-type}} {{/vendorExtensions.x-is-value-type}}
){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}}
( (
this.{{name}} == input.{{name}} || {{name}} == input.{{name}} ||
{{^vendorExtensions.x-is-value-type}}this.{{name}} != null && {{^vendorExtensions.x-is-value-type}}{{name}} != null &&
input.{{name}} != null && input.{{name}} != null &&
{{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) {{/vendorExtensions.x-is-value-type}}{{name}}.SequenceEqual(input.{{name}})
){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} ){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}} {{#isAdditionalPropertiesTrue}}
{{^parentModel}} {{^parentModel}}
&& (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); && (AdditionalProperties.Count == input.AdditionalProperties.Count && !AdditionalProperties.Except(input.AdditionalProperties).Any());
{{/parentModel}} {{/parentModel}}
{{/isAdditionalPropertiesTrue}} {{/isAdditionalPropertiesTrue}}
{{/useCompareNetObjects}} {{/useCompareNetObjects}}
@ -272,29 +283,29 @@
{{^parent}} {{^parent}}
int hashCode = 41; int hashCode = 41;
{{/parent}} {{/parent}}
{{#vars}} {{#readOnlyVars}}
{{^vendorExtensions.x-is-value-type}} {{^isNullable}}
if (this.{{name}} != null) hashCode = (hashCode * 59) + {{name}}.GetHashCode();
{ {{/isNullable}}
hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); {{/readOnlyVars}}
} {{#readOnlyVars}}
{{/vendorExtensions.x-is-value-type}} {{#isNullable}}
{{#vendorExtensions.x-is-value-type}}
hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); if ({{name}} != null)
{{/vendorExtensions.x-is-value-type}} hashCode = (hashCode * 59) + {{name}}.GetHashCode();
{{/vars}} {{/isNullable}}
{{/readOnlyVars}}
{{#isAdditionalPropertiesTrue}} {{#isAdditionalPropertiesTrue}}
{{^parentModel}} {{^parentModel}}
if (this.AdditionalProperties != null) hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode();
{
hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode();
}
{{/parentModel}} {{/parentModel}}
{{/isAdditionalPropertiesTrue}} {{/isAdditionalPropertiesTrue}}
return hashCode; return hashCode;
} }
} }
{{/-first}}
{{/readOnlyVars}}
{{#validatable}} {{#validatable}}
{{^parentModel}} {{^parentModel}}
{{>validatable}} {{>validatable}}

View File

@ -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.
*
*/

View File

@ -29,10 +29,125 @@
/// Enum {{name}} for value: {{value}} /// Enum {{name}} for value: {{value}}
/// </summary> /// </summary>
{{#isString}} {{#isString}}
{{^useGenericHost}}
{{! EnumMember not currently supported in System.Text.Json, use a converter instead }}
[EnumMember(Value = "{{{value}}}")] [EnumMember(Value = "{{{value}}}")]
{{/useGenericHost}}
{{/isString}} {{/isString}}
{{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} {{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}}
{{/enumVars}} {{/enumVars}}
{{/allowableValues}} {{/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}}
}
/// <summary>
/// Returns a {{datatypeWithEnum}} from the Json object
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
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();
}
/// <summary>
/// Writes the {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} to the json writer
/// </summary>
/// <param name="writer"></param>
/// <param name="{{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}"></param>
/// <param name="options"></param>
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}}?>
{
/// <summary>
/// Returns a {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} from the Json object
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
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();
}
/// <summary>
/// Writes the DateTime to the json writer
/// </summary>
/// <param name="writer"></param>
/// <param name="{{#lambda.camelcase_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_param}}"></param>
/// <param name="options"></param>
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}}

View File

@ -17,12 +17,61 @@
/// <summary> /// <summary>
/// Enum {{name}} for value: {{value}} /// Enum {{name}} for value: {{value}}
/// </summary> /// </summary>
{{^useGenericHost}}
{{#isString}} {{#isString}}
[EnumMember(Value = "{{{value}}}")] [EnumMember(Value = "{{{value}}}")]
{{/isString}} {{/isString}}
{{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} {{/useGenericHost}}
{{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}}
{{/enumVars}} {{/enumVars}}
{{/allowableValues}} {{/allowableValues}}
} }
{{/isContainer}} {{#useGenericHost}}
/// <summary>
/// Returns a {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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}}
}
/// <summary>
/// Returns equivalent json value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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}}

View File

@ -8,9 +8,11 @@ using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using {{packageName}}.{{apiPackage}}; using {{packageName}}.{{apiPackage}};
using {{packageName}}.{{modelPackage}}; using {{packageName}}.{{modelPackage}};
using {{packageName}}.Client; using {{packageName}}.{{clientPackage}};
using System.Reflection; using System.Reflection;
{{^useGenericHost}}
using Newtonsoft.Json; using Newtonsoft.Json;
{{/useGenericHost}}
{{#models}} {{#models}}
{{#model}} {{#model}}

View File

@ -0,0 +1 @@
{{! if needed users can add this file to their templates folder to append to the csproj }}

View File

@ -35,14 +35,14 @@
<PackageReference Include="RestSharp" Version="108.0.2" /> <PackageReference Include="RestSharp" Version="108.0.2" />
{{/useRestSharp}} {{/useRestSharp}}
{{#useGenericHost}} {{#useGenericHost}}
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="{{^netStandard}}6.0.0{{/netStandard}}{{#netStandard}}5.0.0{{/netStandard}}" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="{{^netStandard}}6.0.1{{/netStandard}}{{#netStandard}}5.0.0{{/netStandard}}" />
{{#supportsRetry}} {{#supportsRetry}}
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="{{^netStandard}}6.0.4{{/netStandard}}{{#netStandard}}5.0.1{{/netStandard}}" />
{{/supportsRetry}} {{/supportsRetry}}
{{/useGenericHost}} {{/useGenericHost}}
{{#supportsRetry}} {{#supportsRetry}}
<PackageReference Include="Polly" Version="7.2.3" /> <PackageReference Include="Polly" Version="{{^netStandard}}7.2.3{{/netStandard}}{{#netStandard}}7.2.3{{/netStandard}}" />
{{/supportsRetry}} {{/supportsRetry}}
{{#validatable}} {{#validatable}}
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
@ -61,4 +61,4 @@
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
{{/net48}} {{/net48}}
</ItemGroup> </ItemGroup>
</Project> {{>netcore_project.additions}}</Project>

View File

@ -0,0 +1 @@
{{! if needed users can add this file to their templates folder to append to the csproj }}

View File

@ -9,13 +9,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.2" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="{{^netStandard}}17.1.0{{/netStandard}}{{#netStandard}}15.9.2{{/netStandard}}" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="{{^netStandard}}2.4.1{{/netStandard}}{{#netStandard}}2.4.1{{/netStandard}}" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="{{^netStandard}}2.4.3{{/netStandard}}{{#netStandard}}2.4.1{{/netStandard}}" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\{{packageName}}\{{packageName}}.csproj" /> <ProjectReference Include="..\{{packageName}}\{{packageName}}.csproj" />
</ItemGroup> </ItemGroup>
{{>netcore_testproject.additions}}</Project>
</Project>

View File

@ -16,5 +16,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Org.OpenAPITools\Org.OpenAPITools.csproj" /> <ProjectReference Include="..\Org.OpenAPITools\Org.OpenAPITools.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -16,5 +16,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Org.OpenAPITools\Org.OpenAPITools.csproj" /> <ProjectReference Include="..\Org.OpenAPITools\Org.OpenAPITools.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -92,31 +92,38 @@ docs/scripts/git_push.ps1
docs/scripts/git_push.sh docs/scripts/git_push.sh
src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs
src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj
src/Org.OpenAPITools.Test/README.md
src/Org.OpenAPITools/Api/AnotherFakeApi.cs src/Org.OpenAPITools/Api/AnotherFakeApi.cs
src/Org.OpenAPITools/Api/DefaultApi.cs src/Org.OpenAPITools/Api/DefaultApi.cs
src/Org.OpenAPITools/Api/FakeApi.cs src/Org.OpenAPITools/Api/FakeApi.cs
src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs
src/Org.OpenAPITools/Api/IApi.cs
src/Org.OpenAPITools/Api/PetApi.cs src/Org.OpenAPITools/Api/PetApi.cs
src/Org.OpenAPITools/Api/StoreApi.cs src/Org.OpenAPITools/Api/StoreApi.cs
src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiFactory.cs
src/Org.OpenAPITools/Client/ApiKeyToken.cs src/Org.OpenAPITools/Client/ApiKeyToken.cs
src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs
src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs
src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BasicToken.cs
src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/BearerToken.cs
src/Org.OpenAPITools/Client/ClientUtils.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/HostConfiguration.cs
src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs
src/Org.OpenAPITools/Client/HttpSigningToken.cs src/Org.OpenAPITools/Client/HttpSigningToken.cs
src/Org.OpenAPITools/Client/IApi.cs
src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs
src/Org.OpenAPITools/Client/OAuthToken.cs src/Org.OpenAPITools/Client/OAuthToken.cs
src/Org.OpenAPITools/Client/OpenAPIDateJsonConverter.cs
src/Org.OpenAPITools/Client/RateLimitProvider`1.cs src/Org.OpenAPITools/Client/RateLimitProvider`1.cs
src/Org.OpenAPITools/Client/TokenBase.cs src/Org.OpenAPITools/Client/TokenBase.cs
src/Org.OpenAPITools/Client/TokenContainer`1.cs src/Org.OpenAPITools/Client/TokenContainer`1.cs
src/Org.OpenAPITools/Client/TokenProvider`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/Activity.cs
src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs
src/Org.OpenAPITools/Model/AdditionalPropertiesClass.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/Whale.cs
src/Org.OpenAPITools/Model/Zebra.cs src/Org.OpenAPITools/Model/Zebra.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj src/Org.OpenAPITools/Org.OpenAPITools.csproj
src/Org.OpenAPITools/README.md

View File

@ -1,259 +1 @@
# Created with Openapi Generator # Created with Openapi Generator
<a name="cli"></a>
## 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 "<path>/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate `
-g csharp-netcore `
-i <your-swagger-file>.yaml `
-o <your-output-folder> `
--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
```
<a name="usage"></a>
## 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<IAnotherFakeApi>();
ApiResponse<ModelClient?> 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("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, ApiKeyToken>();
// the type of token here depends on the api security specifications
ApiKeyToken token = new("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, ApiKeyToken>();
// the type of token here depends on the api security specifications
ApiKeyToken token = new("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, ApiKeyToken>();
// the type of token here depends on the api security specifications
ApiKeyToken token = new("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, ApiKeyToken>();
// the type of token here depends on the api security specifications
ApiKeyToken token = new("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, ApiKeyToken>();
// the type of token here depends on the api security specifications
ApiKeyToken token = new("<your token>");
options.AddTokens(token);
// optionally choose the method the tokens will be provided with, default is RateLimitProvider
options.UseProvider<RateLimitProvider<ApiKeyToken>, 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
);
});
}
}
```
<a name="questions"></a>
## 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<T> 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.
<a name="dependencies"></a>
## 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
<a name="documentation-for-authorization"></a>
## Documentation for Authorization
Authentication schemes defined for the API:
<a name="api_key"></a>
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
<a name="api_key_query"></a>
### api_key_query
- **Type**: API key
- **API key parameter name**: api_key_query
- **Location**: URL query string
<a name="bearer_test"></a>
### bearer_test
- **Type**: Bearer Authentication
<a name="http_basic_test"></a>
### http_basic_test
- **Type**: HTTP basic authentication
<a name="http_signature_test"></a>
### http_signature_test
<a name="petstore_auth"></a>
### 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: \&quot; \\
## [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.

View File

@ -631,7 +631,7 @@ No authorization required
<a name="testbodywithqueryparams"></a> <a name="testbodywithqueryparams"></a>
# **TestBodyWithQueryParams** # **TestBodyWithQueryParams**
> void TestBodyWithQueryParams (string query, User user) > void TestBodyWithQueryParams (User user, string query)
@ -652,12 +652,12 @@ namespace Example
Configuration config = new Configuration(); Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io:80/v2"; config.BasePath = "http://petstore.swagger.io:80/v2";
var apiInstance = new FakeApi(config); var apiInstance = new FakeApi(config);
var query = "query_example"; // string |
var user = new User(); // User | var user = new User(); // User |
var query = "query_example"; // string |
try try
{ {
apiInstance.TestBodyWithQueryParams(query, user); apiInstance.TestBodyWithQueryParams(user, query);
} }
catch (ApiException e) catch (ApiException e)
{ {
@ -676,7 +676,7 @@ This returns an ApiResponse object which contains the response data, status code
```csharp ```csharp
try try
{ {
apiInstance.TestBodyWithQueryParamsWithHttpInfo(query, user); apiInstance.TestBodyWithQueryParamsWithHttpInfo(user, query);
} }
catch (ApiException e) catch (ApiException e)
{ {
@ -690,8 +690,8 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **query** | **string** | | |
| **user** | [**User**](User.md) | | | | **user** | [**User**](User.md) | | |
| **query** | **string** | | |
### Return type ### Return type
@ -807,7 +807,7 @@ No authorization required
<a name="testendpointparameters"></a> <a name="testendpointparameters"></a>
# **TestEndpointParameters** # **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 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
@ -834,17 +834,17 @@ namespace Example
config.Password = "YOUR_PASSWORD"; config.Password = "YOUR_PASSWORD";
var apiInstance = new FakeApi(config); 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 number = 8.14D; // decimal | None
var _double = 1.2D; // double | None var _double = 1.2D; // double | None
var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | 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 integer = 56; // int? | None (optional)
var int32 = 56; // int? | None (optional) var int32 = 56; // int? | None (optional)
var int64 = 789L; // long? | None (optional) var int64 = 789L; // long? | None (optional)
var _float = 3.4F; // float? | None (optional)
var _string = "_string_example"; // string? | 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 password = "password_example"; // string? | None (optional)
var callback = "callback_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") 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 try
{ {
// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 // 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) catch (ApiException e)
{ {
@ -872,7 +872,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 // 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) catch (ApiException e)
{ {
@ -886,17 +886,17 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **_byte** | **byte[]** | None | |
| **number** | **decimal** | None | | | **number** | **decimal** | None | |
| **_double** | **double** | None | | | **_double** | **double** | None | |
| **patternWithoutDelimiter** | **string** | 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] | | **integer** | **int?** | None | [optional] |
| **int32** | **int?** | None | [optional] | | **int32** | **int?** | None | [optional] |
| **int64** | **long?** | None | [optional] | | **int64** | **long?** | None | [optional] |
| **_float** | **float?** | None | [optional] |
| **_string** | **string?** | None | [optional] | | **_string** | **string?** | None | [optional] |
| **binary** | **System.IO.Stream?****System.IO.Stream?** | None | [optional] |
| **date** | **DateTime?** | None | [optional] |
| **password** | **string?** | None | [optional] | | **password** | **string?** | None | [optional] |
| **callback** | **string?** | None | [optional] | | **callback** | **string?** | None | [optional] |
| **dateTime** | **DateTime?** | None | [optional] [default to &quot;2010-02-01T10:20:10.111110+01:00&quot;] | | **dateTime** | **DateTime?** | None | [optional] [default to &quot;2010-02-01T10:20:10.111110+01:00&quot;] |
@ -925,7 +925,7 @@ void (empty response body)
<a name="testenumparameters"></a> <a name="testenumparameters"></a>
# **TestEnumParameters** # **TestEnumParameters**
> void TestEnumParameters (List<string>? enumHeaderStringArray = null, List<string>? enumQueryStringArray = null, int? enumQueryInteger = null, double? enumQueryDouble = null, string? enumHeaderString = null, string? enumQueryString = null, List<string>? enumFormStringArray = null, string? enumFormString = null) > void TestEnumParameters (List<string>? enumHeaderStringArray = null, List<string>? enumQueryStringArray = null, double? enumQueryDouble = null, int? enumQueryInteger = null, List<string>? enumFormStringArray = null, string? enumHeaderString = null, string? enumQueryString = null, string? enumFormString = null)
To test enum parameters To test enum parameters
@ -950,17 +950,17 @@ namespace Example
var apiInstance = new FakeApi(config); var apiInstance = new FakeApi(config);
var enumHeaderStringArray = new List<string>?(); // List<string>? | Header parameter enum test (string array) (optional) var enumHeaderStringArray = new List<string>?(); // List<string>? | Header parameter enum test (string array) (optional)
var enumQueryStringArray = new List<string>?(); // List<string>? | Query parameter enum test (string array) (optional) var enumQueryStringArray = new List<string>?(); // List<string>? | 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 enumQueryDouble = 1.1D; // double? | Query parameter enum test (double) (optional)
var enumQueryInteger = 1; // int? | Query parameter enum test (double) (optional)
var enumFormStringArray = new List<string>?(); // List<string>? | Form parameter enum test (string array) (optional) (default to $)
var enumHeaderString = "_abc"; // string? | Header parameter enum test (string) (optional) (default to -efg) 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 enumQueryString = "_abc"; // string? | Query parameter enum test (string) (optional) (default to -efg)
var enumFormStringArray = new List<string>?(); // List<string>? | Form parameter enum test (string array) (optional) (default to $)
var enumFormString = "_abc"; // string? | Form parameter enum test (string) (optional) (default to -efg) var enumFormString = "_abc"; // string? | Form parameter enum test (string) (optional) (default to -efg)
try try
{ {
// To test enum parameters // 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) catch (ApiException e)
{ {
@ -980,7 +980,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// To test enum parameters // 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) catch (ApiException e)
{ {
@ -996,11 +996,11 @@ catch (ApiException e)
|------|------|-------------|-------| |------|------|-------------|-------|
| **enumHeaderStringArray** | [**List&lt;string&gt;?**](string.md) | Header parameter enum test (string array) | [optional] | | **enumHeaderStringArray** | [**List&lt;string&gt;?**](string.md) | Header parameter enum test (string array) | [optional] |
| **enumQueryStringArray** | [**List&lt;string&gt;?**](string.md) | Query parameter enum test (string array) | [optional] | | **enumQueryStringArray** | [**List&lt;string&gt;?**](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] | | **enumQueryDouble** | **double?** | Query parameter enum test (double) | [optional] |
| **enumQueryInteger** | **int?** | Query parameter enum test (double) | [optional] |
| **enumFormStringArray** | [**List&lt;string&gt;?**](string.md) | Form parameter enum test (string array) | [optional] [default to $] |
| **enumHeaderString** | **string?** | Header parameter enum test (string) | [optional] [default to -efg] | | **enumHeaderString** | **string?** | Header parameter enum test (string) | [optional] [default to -efg] |
| **enumQueryString** | **string?** | Query parameter enum test (string) | [optional] [default to -efg] | | **enumQueryString** | **string?** | Query parameter enum test (string) | [optional] [default to -efg] |
| **enumFormStringArray** | [**List&lt;string&gt;?**](string.md) | Form parameter enum test (string array) | [optional] [default to $] |
| **enumFormString** | **string?** | Form parameter enum test (string) | [optional] [default to -efg] | | **enumFormString** | **string?** | Form parameter enum test (string) | [optional] [default to -efg] |
### Return type ### Return type
@ -1027,7 +1027,7 @@ No authorization required
<a name="testgroupparameters"></a> <a name="testgroupparameters"></a>
# **TestGroupParameters** # **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) Fake endpoint to test group parameters (optional)
@ -1053,17 +1053,17 @@ namespace Example
config.AccessToken = "YOUR_BEARER_TOKEN"; config.AccessToken = "YOUR_BEARER_TOKEN";
var apiInstance = new FakeApi(config); var apiInstance = new FakeApi(config);
var requiredStringGroup = 56; // int | Required String in group parameters
var requiredBooleanGroup = true; // bool | Required Boolean 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 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 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) var int64Group = 789L; // long? | Integer in group parameters (optional)
try try
{ {
// Fake endpoint to test group parameters (optional) // 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) catch (ApiException e)
{ {
@ -1083,7 +1083,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// Fake endpoint to test group parameters (optional) // 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) catch (ApiException e)
{ {
@ -1097,11 +1097,11 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **requiredStringGroup** | **int** | Required String in group parameters | |
| **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | | **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | |
| **requiredStringGroup** | **int** | Required String in group parameters | |
| **requiredInt64Group** | **long** | Required Integer in group parameters | | | **requiredInt64Group** | **long** | Required Integer in group parameters | |
| **stringGroup** | **int?** | String in group parameters | [optional] |
| **booleanGroup** | **bool?** | Boolean 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] | | **int64Group** | **long?** | Integer in group parameters | [optional] |
### Return type ### Return type

View File

@ -664,7 +664,7 @@ void (empty response body)
<a name="uploadfile"></a> <a name="uploadfile"></a>
# **UploadFile** # **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 uploads an image
@ -689,13 +689,13 @@ namespace Example
var apiInstance = new PetApi(config); var apiInstance = new PetApi(config);
var petId = 789L; // long | ID of pet to update 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 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 try
{ {
// uploads an image // uploads an image
ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); ApiResponse result = apiInstance.UploadFile(petId, file, additionalMetadata);
Debug.WriteLine(result); Debug.WriteLine(result);
} }
catch (ApiException e) catch (ApiException e)
@ -716,7 +716,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// uploads an image // uploads an image
ApiResponse<ApiResponse> response = apiInstance.UploadFileWithHttpInfo(petId, additionalMetadata, file); ApiResponse<ApiResponse> response = apiInstance.UploadFileWithHttpInfo(petId, file, additionalMetadata);
Debug.Write("Status Code: " + response.StatusCode); Debug.Write("Status Code: " + response.StatusCode);
Debug.Write("Response Headers: " + response.Headers); Debug.Write("Response Headers: " + response.Headers);
Debug.Write("Response Body: " + response.Data); Debug.Write("Response Body: " + response.Data);
@ -734,8 +734,8 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **petId** | **long** | ID of pet to update | | | **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] | | **file** | **System.IO.Stream?****System.IO.Stream?** | file to upload | [optional] |
| **additionalMetadata** | **string?** | Additional data to pass to server | [optional] |
### Return type ### Return type
@ -760,7 +760,7 @@ catch (ApiException e)
<a name="uploadfilewithrequiredfile"></a> <a name="uploadfilewithrequiredfile"></a>
# **UploadFileWithRequiredFile** # **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) uploads an image (required)
@ -784,14 +784,14 @@ namespace Example
config.AccessToken = "YOUR_ACCESS_TOKEN"; config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config); 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 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) var additionalMetadata = "additionalMetadata_example"; // string? | Additional data to pass to server (optional)
try try
{ {
// uploads an image (required) // uploads an image (required)
ApiResponse result = apiInstance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); ApiResponse result = apiInstance.UploadFileWithRequiredFile(requiredFile, petId, additionalMetadata);
Debug.WriteLine(result); Debug.WriteLine(result);
} }
catch (ApiException e) catch (ApiException e)
@ -812,7 +812,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// uploads an image (required) // uploads an image (required)
ApiResponse<ApiResponse> response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); ApiResponse<ApiResponse> response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(requiredFile, petId, additionalMetadata);
Debug.Write("Status Code: " + response.StatusCode); Debug.Write("Status Code: " + response.StatusCode);
Debug.Write("Response Headers: " + response.Headers); Debug.Write("Response Headers: " + response.Headers);
Debug.Write("Response Body: " + response.Data); Debug.Write("Response Body: " + response.Data);
@ -829,8 +829,8 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **petId** | **long** | ID of pet to update | |
| **requiredFile** | **System.IO.Stream****System.IO.Stream** | file to upload | | | **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] | | **additionalMetadata** | **string?** | Additional data to pass to server | [optional] |
### Return type ### Return type

View File

@ -623,7 +623,7 @@ No authorization required
<a name="updateuser"></a> <a name="updateuser"></a>
# **UpdateUser** # **UpdateUser**
> void UpdateUser (string username, User user) > void UpdateUser (User user, string username)
Updated user Updated user
@ -646,13 +646,13 @@ namespace Example
Configuration config = new Configuration(); Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io:80/v2"; config.BasePath = "http://petstore.swagger.io:80/v2";
var apiInstance = new UserApi(config); 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 user = new User(); // User | Updated user object
var username = "username_example"; // string | name that need to be deleted
try try
{ {
// Updated user // Updated user
apiInstance.UpdateUser(username, user); apiInstance.UpdateUser(user, username);
} }
catch (ApiException e) catch (ApiException e)
{ {
@ -672,7 +672,7 @@ This returns an ApiResponse object which contains the response data, status code
try try
{ {
// Updated user // Updated user
apiInstance.UpdateUserWithHttpInfo(username, user); apiInstance.UpdateUserWithHttpInfo(user, username);
} }
catch (ApiException e) catch (ApiException e)
{ {
@ -686,8 +686,8 @@ catch (ApiException e)
| Name | Type | Description | Notes | | Name | Type | Description | Notes |
|------|------|-------------|-------| |------|------|-------------|-------|
| **username** | **string** | name that need to be deleted | |
| **user** | [**User**](User.md) | Updated user object | | | **user** | [**User**](User.md) | Updated user object | |
| **username** | **string** | name that need to be deleted | |
### Return type ### Return type

View File

@ -4,14 +4,14 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**MapProperty** | **Dictionary&lt;string, string&gt;** | | [optional] **EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it&#39;s an empty map. | [optional]
**MapOfMapProperty** | **Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;** | | [optional] **MapOfMapProperty** | **Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;** | | [optional]
**Anytype1** | **Object** | | [optional] **MapProperty** | **Dictionary&lt;string, string&gt;** | | [optional]
**MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional]
**MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional]
**MapWithUndeclaredPropertiesAnytype3** | **Dictionary&lt;string, Object&gt;** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary&lt;string, Object&gt;** | | [optional]
**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it&#39;s an empty map. | [optional]
**MapWithUndeclaredPropertiesString** | **Dictionary&lt;string, string&gt;** | | [optional] **MapWithUndeclaredPropertiesString** | **Dictionary&lt;string, string&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -5,8 +5,8 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Code** | **int** | | [optional] **Code** | **int** | | [optional]
**Type** | **string** | | [optional]
**Message** | **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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,9 +4,9 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**ArrayOfString** | **List&lt;string&gt;** | | [optional]
**ArrayArrayOfInteger** | **List&lt;List&lt;long&gt;&gt;** | | [optional] **ArrayArrayOfInteger** | **List&lt;List&lt;long&gt;&gt;** | | [optional]
**ArrayArrayOfModel** | **List&lt;List&lt;ReadOnlyFirst&gt;&gt;** | | [optional] **ArrayArrayOfModel** | **List&lt;List&lt;ReadOnlyFirst&gt;&gt;** | | [optional]
**ArrayOfString** | **List&lt;string&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,12 +4,12 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**SmallCamel** | **string** | | [optional] **ATT_NAME** | **string** | Name of the pet | [optional]
**CapitalCamel** | **string** | | [optional] **CapitalCamel** | **string** | | [optional]
**SmallSnake** | **string** | | [optional]
**CapitalSnake** | **string** | | [optional] **CapitalSnake** | **string** | | [optional]
**SCAETHFlowPoints** | **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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,8 +4,8 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Name** | **string** | | [default to "default-name"]
**Id** | **long** | | [optional] **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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -5,7 +5,7 @@ Model for testing model with \"_class\" property
Name | Type | Description | Notes 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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -6,8 +6,8 @@ Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**MainShape** | [**Shape**](Shape.md) | | [optional] **MainShape** | [**Shape**](Shape.md) | | [optional]
**ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional]
**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional]
**Shapes** | [**List&lt;Shape&gt;**](Shape.md) | | [optional] **Shapes** | [**List&lt;Shape&gt;**](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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,8 +4,8 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**JustSymbol** | **string** | | [optional]
**ArrayEnum** | **List&lt;EnumArrays.ArrayEnumEnum&gt;** | | [optional] **ArrayEnum** | **List&lt;EnumArrays.ArrayEnumEnum&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,15 +4,15 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**EnumStringRequired** | **string** | |
**EnumString** | **string** | | [optional]
**EnumInteger** | **int** | | [optional] **EnumInteger** | **int** | | [optional]
**EnumIntegerOnly** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional]
**EnumNumber** | **double** | | [optional] **EnumNumber** | **double** | | [optional]
**OuterEnum** | **OuterEnum** | | [optional] **EnumString** | **string** | | [optional]
**OuterEnumInteger** | **OuterEnumInteger** | | [optional] **EnumStringRequired** | **string** | |
**OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] **OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional]
**OuterEnumInteger** | **OuterEnumInteger** | | [optional]
**OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,7 +4,7 @@
Name | Type | Description | Notes 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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,22 +4,22 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Number** | **decimal** | | **Binary** | **System.IO.Stream** | | [optional]
**Byte** | **byte[]** | | **ByteProperty** | **byte[]** | |
**Date** | **DateTime** | | **Date** | **DateTime** | |
**Password** | **string** | | **DateTime** | **DateTime** | | [optional]
**Integer** | **int** | | [optional] **DecimalProperty** | **decimal** | | [optional]
**DoubleProperty** | **double** | | [optional]
**FloatProperty** | **float** | | [optional]
**Int32** | **int** | | [optional] **Int32** | **int** | | [optional]
**Int64** | **long** | | [optional] **Int64** | **long** | | [optional]
**Float** | **float** | | [optional] **Integer** | **int** | | [optional]
**Double** | **double** | | [optional] **Number** | **decimal** | |
**Decimal** | **decimal** | | [optional] **Password** | **string** | |
**String** | **string** | | [optional]
**Binary** | **System.IO.Stream** | | [optional]
**DateTime** | **DateTime** | | [optional]
**Uuid** | **Guid** | | [optional]
**PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] **PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional]
**PatternWithDigitsAndDelimiter** | **string** | A string starting with &#39;image_&#39; (case insensitive) and one to three digits following i.e. Image_01. | [optional] **PatternWithDigitsAndDelimiter** | **string** | A string starting with &#39;image_&#39; (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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,10 +4,10 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**MapMapOfString** | **Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;** | | [optional]
**MapOfEnumString** | **Dictionary&lt;string, MapTest.InnerEnum&gt;** | | [optional]
**DirectMap** | **Dictionary&lt;string, bool&gt;** | | [optional] **DirectMap** | **Dictionary&lt;string, bool&gt;** | | [optional]
**IndirectMap** | **Dictionary&lt;string, bool&gt;** | | [optional] **IndirectMap** | **Dictionary&lt;string, bool&gt;** | | [optional]
**MapMapOfString** | **Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;** | | [optional]
**MapOfEnumString** | **Dictionary&lt;string, MapTest.InnerEnum&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,9 +4,9 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Uuid** | **Guid** | | [optional]
**DateTime** | **DateTime** | | [optional] **DateTime** | **DateTime** | | [optional]
**Map** | [**Dictionary&lt;string, Animal&gt;**](Animal.md) | | [optional] **Map** | [**Dictionary&lt;string, Animal&gt;**](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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -5,8 +5,8 @@ Model for testing model name starting with number
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**ClassProperty** | **string** | | [optional]
**Name** | **int** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,7 +4,7 @@
Name | Type | Description | Notes 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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -6,8 +6,8 @@ Model for testing model name same as property name
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**NameProperty** | **int** | | **NameProperty** | **int** | |
**SnakeCase** | **int** | | [optional] [readonly]
**Property** | **string** | | [optional] **Property** | **string** | | [optional]
**SnakeCase** | **int** | | [optional] [readonly]
**_123Number** | **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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,18 +4,18 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**IntegerProp** | **int?** | | [optional] **ArrayItemsNullable** | **List&lt;Object&gt;** | | [optional]
**NumberProp** | **decimal?** | | [optional] **ObjectItemsNullable** | **Dictionary&lt;string, Object&gt;** | | [optional]
**ArrayAndItemsNullableProp** | **List&lt;Object&gt;** | | [optional]
**ArrayNullableProp** | **List&lt;Object&gt;** | | [optional]
**BooleanProp** | **bool?** | | [optional] **BooleanProp** | **bool?** | | [optional]
**StringProp** | **string** | | [optional]
**DateProp** | **DateTime?** | | [optional] **DateProp** | **DateTime?** | | [optional]
**DatetimeProp** | **DateTime?** | | [optional] **DatetimeProp** | **DateTime?** | | [optional]
**ArrayNullableProp** | **List&lt;Object&gt;** | | [optional] **IntegerProp** | **int?** | | [optional]
**ArrayAndItemsNullableProp** | **List&lt;Object&gt;** | | [optional] **NumberProp** | **decimal?** | | [optional]
**ArrayItemsNullable** | **List&lt;Object&gt;** | | [optional]
**ObjectNullableProp** | **Dictionary&lt;string, Object&gt;** | | [optional]
**ObjectAndItemsNullableProp** | **Dictionary&lt;string, Object&gt;** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary&lt;string, Object&gt;** | | [optional]
**ObjectItemsNullable** | **Dictionary&lt;string, Object&gt;** | | [optional] **ObjectNullableProp** | **Dictionary&lt;string, Object&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,10 +4,10 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Uuid** | **string** | | [optional]
**Id** | **decimal** | | [optional]
**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional]
**Bars** | **List&lt;string&gt;** | | [optional] **Bars** | **List&lt;string&gt;** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,9 +4,9 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**MyBoolean** | **bool** | | [optional]
**MyNumber** | **decimal** | | [optional] **MyNumber** | **decimal** | | [optional]
**MyString** | **string** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,12 +4,12 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Category** | [**Category**](Category.md) | | [optional]
**Id** | **long** | | [optional]
**Name** | **string** | | **Name** | **string** | |
**PhotoUrls** | **List&lt;string&gt;** | | **PhotoUrls** | **List&lt;string&gt;** | |
**Id** | **long** | | [optional]
**Category** | [**Category**](Category.md) | | [optional]
**Tags** | [**List&lt;Tag&gt;**](Tag.md) | | [optional]
**Status** | **string** | pet status in the store | [optional] **Status** | **string** | pet status in the store | [optional]
**Tags** | [**List&lt;Tag&gt;**](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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,8 +4,8 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**SpecialPropertyName** | **long** | | [optional]
**SpecialModelNameProperty** | **string** | | [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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -4,18 +4,18 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**Username** | **string** | | [optional]
**FirstName** | **string** | | [optional]
**LastName** | **string** | | [optional]
**Email** | **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 &#39;null&#39; value. | [optional]
**Password** | **string** | | [optional] **Password** | **string** | | [optional]
**Phone** | **string** | | [optional] **Phone** | **string** | | [optional]
**UserStatus** | **int** | User Status | [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 &#39;null&#39; value. | [optional] **Username** | **string** | | [optional]
**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the &#39;null&#39; value. | [optional]
**AnyTypeProp** | **Object** | test code generation for any type Here the &#39;type&#39; 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] **AnyTypeProp** | **Object** | test code generation for any type Here the &#39;type&#39; 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 &#39;type&#39; attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The &#39;nullable&#39; attribute does not change the allowed values. | [optional] **AnyTypePropNullable** | **Object** | test code generation for any type Here the &#39;type&#39; attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The &#39;nullable&#39; 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 &#39;null&#39; 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) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class AnotherFakeApiTests : ApiTestsBase public sealed class AnotherFakeApiTests : ApiTestsBase
{ {
private readonly IAnotherFakeApi _instance; private readonly IApi.IAnotherFakeApi _instance;
public AnotherFakeApiTests(): base(Array.Empty<string>()) public AnotherFakeApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IAnotherFakeApi>(); _instance = _host.Services.GetRequiredService<IApi.IAnotherFakeApi>();
} }

View File

@ -12,6 +12,7 @@ using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Org.OpenAPITools.Client; 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) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureApi((context, options) => .ConfigureApi((context, services, options) =>
{ {
ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration["<token>"], timeout: TimeSpan.FromSeconds(1)); ApiKeyToken apiKeyToken = new ApiKeyToken(context.Configuration["<token>"], timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class DefaultApiTests : ApiTestsBase public sealed class DefaultApiTests : ApiTestsBase
{ {
private readonly IDefaultApi _instance; private readonly IApi.IDefaultApi _instance;
public DefaultApiTests(): base(Array.Empty<string>()) public DefaultApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IDefaultApi>(); _instance = _host.Services.GetRequiredService<IApi.IDefaultApi>();
} }

View File

@ -13,7 +13,8 @@ using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Extensions;
using Xunit; using Xunit;
namespace Org.OpenAPITools.Test.Api namespace Org.OpenAPITools.Test.Api
@ -24,7 +25,7 @@ namespace Org.OpenAPITools.Test.Api
public class DependencyInjectionTest public class DependencyInjectionTest
{ {
private readonly IHost _hostUsingConfigureWithoutAClient = private readonly IHost _hostUsingConfigureWithoutAClient =
Host.CreateDefaultBuilder(Array.Empty<string>()).ConfigureApi((context, options) => Host.CreateDefaultBuilder(Array.Empty<string>()).ConfigureApi((context, services, options) =>
{ {
ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1)); ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);
@ -45,7 +46,7 @@ namespace Org.OpenAPITools.Test.Api
.Build(); .Build();
private readonly IHost _hostUsingConfigureWithAClient = private readonly IHost _hostUsingConfigureWithAClient =
Host.CreateDefaultBuilder(Array.Empty<string>()).ConfigureApi((context, options) => Host.CreateDefaultBuilder(Array.Empty<string>()).ConfigureApi((context, services, options) =>
{ {
ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1)); ApiKeyToken apiKeyToken = new ApiKeyToken($"<token>", timeout: TimeSpan.FromSeconds(1));
options.AddTokens(apiKeyToken); options.AddTokens(apiKeyToken);
@ -121,25 +122,25 @@ namespace Org.OpenAPITools.Test.Api
[Fact] [Fact]
public void ConfigureApiWithAClientTest() public void ConfigureApiWithAClientTest()
{ {
var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IAnotherFakeApi>(); var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IAnotherFakeApi>();
Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null);
var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IDefaultApi>(); var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IDefaultApi>();
Assert.True(defaultApi.HttpClient.BaseAddress != null); Assert.True(defaultApi.HttpClient.BaseAddress != null);
var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IFakeApi>(); var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IFakeApi>();
Assert.True(fakeApi.HttpClient.BaseAddress != null); Assert.True(fakeApi.HttpClient.BaseAddress != null);
var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService<IFakeClassnameTags123Api>(); var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IFakeClassnameTags123Api>();
Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null);
var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IPetApi>(); var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IPetApi>();
Assert.True(petApi.HttpClient.BaseAddress != null); Assert.True(petApi.HttpClient.BaseAddress != null);
var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IStoreApi>(); var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IStoreApi>();
Assert.True(storeApi.HttpClient.BaseAddress != null); Assert.True(storeApi.HttpClient.BaseAddress != null);
var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IUserApi>(); var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService<IApi.IUserApi>();
Assert.True(userApi.HttpClient.BaseAddress != null); Assert.True(userApi.HttpClient.BaseAddress != null);
} }
@ -149,25 +150,25 @@ namespace Org.OpenAPITools.Test.Api
[Fact] [Fact]
public void ConfigureApiWithoutAClientTest() public void ConfigureApiWithoutAClientTest()
{ {
var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IAnotherFakeApi>(); var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IAnotherFakeApi>();
Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null);
var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IDefaultApi>(); var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IDefaultApi>();
Assert.True(defaultApi.HttpClient.BaseAddress != null); Assert.True(defaultApi.HttpClient.BaseAddress != null);
var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IFakeApi>(); var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IFakeApi>();
Assert.True(fakeApi.HttpClient.BaseAddress != null); Assert.True(fakeApi.HttpClient.BaseAddress != null);
var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IFakeClassnameTags123Api>(); var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IFakeClassnameTags123Api>();
Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null);
var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IPetApi>(); var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IPetApi>();
Assert.True(petApi.HttpClient.BaseAddress != null); Assert.True(petApi.HttpClient.BaseAddress != null);
var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IStoreApi>(); var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IStoreApi>();
Assert.True(storeApi.HttpClient.BaseAddress != null); Assert.True(storeApi.HttpClient.BaseAddress != null);
var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IUserApi>(); var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<IApi.IUserApi>();
Assert.True(userApi.HttpClient.BaseAddress != null); Assert.True(userApi.HttpClient.BaseAddress != null);
} }
@ -177,25 +178,25 @@ namespace Org.OpenAPITools.Test.Api
[Fact] [Fact]
public void AddApiWithAClientTest() public void AddApiWithAClientTest()
{ {
var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IAnotherFakeApi>(); var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IAnotherFakeApi>();
Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null);
var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService<IDefaultApi>(); var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IDefaultApi>();
Assert.True(defaultApi.HttpClient.BaseAddress != null); Assert.True(defaultApi.HttpClient.BaseAddress != null);
var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IFakeApi>(); var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IFakeApi>();
Assert.True(fakeApi.HttpClient.BaseAddress != null); Assert.True(fakeApi.HttpClient.BaseAddress != null);
var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService<IFakeClassnameTags123Api>(); var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IFakeClassnameTags123Api>();
Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null);
var petApi = _hostUsingAddWithAClient.Services.GetRequiredService<IPetApi>(); var petApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IPetApi>();
Assert.True(petApi.HttpClient.BaseAddress != null); Assert.True(petApi.HttpClient.BaseAddress != null);
var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IStoreApi>(); var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IStoreApi>();
Assert.True(storeApi.HttpClient.BaseAddress != null); Assert.True(storeApi.HttpClient.BaseAddress != null);
var userApi = _hostUsingAddWithAClient.Services.GetRequiredService<IUserApi>(); var userApi = _hostUsingAddWithAClient.Services.GetRequiredService<IApi.IUserApi>();
Assert.True(userApi.HttpClient.BaseAddress != null); Assert.True(userApi.HttpClient.BaseAddress != null);
} }
@ -205,25 +206,25 @@ namespace Org.OpenAPITools.Test.Api
[Fact] [Fact]
public void AddApiWithoutAClientTest() public void AddApiWithoutAClientTest()
{ {
var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IAnotherFakeApi>(); var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IAnotherFakeApi>();
Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null);
var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IDefaultApi>(); var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IDefaultApi>();
Assert.True(defaultApi.HttpClient.BaseAddress != null); Assert.True(defaultApi.HttpClient.BaseAddress != null);
var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IFakeApi>(); var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IFakeApi>();
Assert.True(fakeApi.HttpClient.BaseAddress != null); Assert.True(fakeApi.HttpClient.BaseAddress != null);
var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService<IFakeClassnameTags123Api>(); var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IFakeClassnameTags123Api>();
Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null);
var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IPetApi>(); var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IPetApi>();
Assert.True(petApi.HttpClient.BaseAddress != null); Assert.True(petApi.HttpClient.BaseAddress != null);
var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IStoreApi>(); var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IStoreApi>();
Assert.True(storeApi.HttpClient.BaseAddress != null); Assert.True(storeApi.HttpClient.BaseAddress != null);
var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IUserApi>(); var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService<IApi.IUserApi>();
Assert.True(userApi.HttpClient.BaseAddress != null); Assert.True(userApi.HttpClient.BaseAddress != null);
} }
} }

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class FakeApiTests : ApiTestsBase public sealed class FakeApiTests : ApiTestsBase
{ {
private readonly IFakeApi _instance; private readonly IApi.IFakeApi _instance;
public FakeApiTests(): base(Array.Empty<string>()) public FakeApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IFakeApi>(); _instance = _host.Services.GetRequiredService<IApi.IFakeApi>();
} }
@ -131,9 +131,9 @@ namespace Org.OpenAPITools.Test.Api
[Fact (Skip = "not implemented")] [Fact (Skip = "not implemented")]
public async Task TestBodyWithQueryParamsAsyncTest() public async Task TestBodyWithQueryParamsAsyncTest()
{ {
string query = default;
User user = default; User user = default;
await _instance.TestBodyWithQueryParamsAsync(query, user); string query = default;
await _instance.TestBodyWithQueryParamsAsync(user, query);
} }
/// <summary> /// <summary>
@ -153,21 +153,21 @@ namespace Org.OpenAPITools.Test.Api
[Fact (Skip = "not implemented")] [Fact (Skip = "not implemented")]
public async Task TestEndpointParametersAsyncTest() public async Task TestEndpointParametersAsyncTest()
{ {
byte[] _byte = default;
decimal number = default; decimal number = default;
double _double = default; double _double = default;
string patternWithoutDelimiter = default; string patternWithoutDelimiter = default;
byte[] _byte = default; DateTime? date = default;
System.IO.Stream? binary = default;
float? _float = default;
int? integer = default; int? integer = default;
int? int32 = default; int? int32 = default;
long? int64 = default; long? int64 = default;
float? _float = default;
string? _string = default; string? _string = default;
System.IO.Stream? binary = default;
DateTime? date = default;
string? password = default; string? password = default;
string? callback = default; string? callback = default;
DateTime? dateTime = 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);
} }
/// <summary> /// <summary>
@ -178,13 +178,13 @@ namespace Org.OpenAPITools.Test.Api
{ {
List<string>? enumHeaderStringArray = default; List<string>? enumHeaderStringArray = default;
List<string>? enumQueryStringArray = default; List<string>? enumQueryStringArray = default;
int? enumQueryInteger = default;
double? enumQueryDouble = default; double? enumQueryDouble = default;
int? enumQueryInteger = default;
List<string>? enumFormStringArray = default;
string? enumHeaderString = default; string? enumHeaderString = default;
string? enumQueryString = default; string? enumQueryString = default;
List<string>? enumFormStringArray = default;
string? enumFormString = 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);
} }
/// <summary> /// <summary>
@ -193,13 +193,13 @@ namespace Org.OpenAPITools.Test.Api
[Fact (Skip = "not implemented")] [Fact (Skip = "not implemented")]
public async Task TestGroupParametersAsyncTest() public async Task TestGroupParametersAsyncTest()
{ {
int requiredStringGroup = default;
bool requiredBooleanGroup = default; bool requiredBooleanGroup = default;
int requiredStringGroup = default;
long requiredInt64Group = default; long requiredInt64Group = default;
int? stringGroup = default;
bool? booleanGroup = default; bool? booleanGroup = default;
int? stringGroup = default;
long? int64Group = default; long? int64Group = default;
await _instance.TestGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); await _instance.TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group);
} }
/// <summary> /// <summary>

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class FakeClassnameTags123ApiTests : ApiTestsBase public sealed class FakeClassnameTags123ApiTests : ApiTestsBase
{ {
private readonly IFakeClassnameTags123Api _instance; private readonly IApi.IFakeClassnameTags123Api _instance;
public FakeClassnameTags123ApiTests(): base(Array.Empty<string>()) public FakeClassnameTags123ApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IFakeClassnameTags123Api>(); _instance = _host.Services.GetRequiredService<IApi.IFakeClassnameTags123Api>();
} }

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class PetApiTests : ApiTestsBase public sealed class PetApiTests : ApiTestsBase
{ {
private readonly IPetApi _instance; private readonly IApi.IPetApi _instance;
public PetApiTests(): base(Array.Empty<string>()) public PetApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IPetApi>(); _instance = _host.Services.GetRequiredService<IApi.IPetApi>();
} }
@ -134,9 +134,9 @@ namespace Org.OpenAPITools.Test.Api
public async Task UploadFileAsyncTest() public async Task UploadFileAsyncTest()
{ {
long petId = default; long petId = default;
string? additionalMetadata = default;
System.IO.Stream? file = 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<ApiResponse>(response); Assert.IsType<ApiResponse>(response);
} }
@ -146,10 +146,10 @@ namespace Org.OpenAPITools.Test.Api
[Fact (Skip = "not implemented")] [Fact (Skip = "not implemented")]
public async Task UploadFileWithRequiredFileAsyncTest() public async Task UploadFileWithRequiredFileAsyncTest()
{ {
long petId = default;
System.IO.Stream requiredFile = default; System.IO.Stream requiredFile = default;
long petId = default;
string? additionalMetadata = default; string? additionalMetadata = default;
var response = await _instance.UploadFileWithRequiredFileAsync(petId, requiredFile, additionalMetadata); var response = await _instance.UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata);
Assert.IsType<ApiResponse>(response); Assert.IsType<ApiResponse>(response);
} }
} }

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class StoreApiTests : ApiTestsBase public sealed class StoreApiTests : ApiTestsBase
{ {
private readonly IStoreApi _instance; private readonly IApi.IStoreApi _instance;
public StoreApiTests(): base(Array.Empty<string>()) public StoreApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IStoreApi>(); _instance = _host.Services.GetRequiredService<IApi.IStoreApi>();
} }

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Org.OpenAPITools.Api; using Org.OpenAPITools.IApi;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
@ -43,11 +43,11 @@ namespace Org.OpenAPITools.Test.Api
/// </summary> /// </summary>
public sealed class UserApiTests : ApiTestsBase public sealed class UserApiTests : ApiTestsBase
{ {
private readonly IUserApi _instance; private readonly IApi.IUserApi _instance;
public UserApiTests(): base(Array.Empty<string>()) public UserApiTests(): base(Array.Empty<string>())
{ {
_instance = _host.Services.GetRequiredService<IUserApi>(); _instance = _host.Services.GetRequiredService<IApi.IUserApi>();
} }
@ -129,9 +129,9 @@ namespace Org.OpenAPITools.Test.Api
[Fact (Skip = "not implemented")] [Fact (Skip = "not implemented")]
public async Task UpdateUserAsyncTest() public async Task UpdateUserAsyncTest()
{ {
string username = default;
User user = default; User user = default;
await _instance.UpdateUserAsync(username, user); string username = default;
await _instance.UpdateUserAsync(user, username);
} }
} }
} }

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {
@ -57,12 +56,12 @@ namespace Org.OpenAPITools.Test.Model
/// <summary> /// <summary>
/// Test the property 'MapProperty' /// Test the property 'EmptyMap'
/// </summary> /// </summary>
[Fact] [Fact]
public void MapPropertyTest() public void EmptyMapTest()
{ {
// TODO unit test for the property 'MapProperty' // TODO unit test for the property 'EmptyMap'
} }
/// <summary> /// <summary>
/// Test the property 'MapOfMapProperty' /// Test the property 'MapOfMapProperty'
@ -73,12 +72,12 @@ namespace Org.OpenAPITools.Test.Model
// TODO unit test for the property 'MapOfMapProperty' // TODO unit test for the property 'MapOfMapProperty'
} }
/// <summary> /// <summary>
/// Test the property 'Anytype1' /// Test the property 'MapProperty'
/// </summary> /// </summary>
[Fact] [Fact]
public void Anytype1Test() public void MapPropertyTest()
{ {
// TODO unit test for the property 'Anytype1' // TODO unit test for the property 'MapProperty'
} }
/// <summary> /// <summary>
/// Test the property 'MapWithUndeclaredPropertiesAnytype1' /// Test the property 'MapWithUndeclaredPropertiesAnytype1'
@ -105,14 +104,6 @@ namespace Org.OpenAPITools.Test.Model
// TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3'
} }
/// <summary> /// <summary>
/// Test the property 'EmptyMap'
/// </summary>
[Fact]
public void EmptyMapTest()
{
// TODO unit test for the property 'EmptyMap'
}
/// <summary>
/// Test the property 'MapWithUndeclaredPropertiesString' /// Test the property 'MapWithUndeclaredPropertiesString'
/// </summary> /// </summary>
[Fact] [Fact]
@ -120,6 +111,14 @@ namespace Org.OpenAPITools.Test.Model
{ {
// TODO unit test for the property 'MapWithUndeclaredPropertiesString' // TODO unit test for the property 'MapWithUndeclaredPropertiesString'
} }
/// <summary>
/// Test the property 'Anytype1'
/// </summary>
[Fact]
public void Anytype1Test()
{
// TODO unit test for the property 'Anytype1'
}
} }

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {
@ -65,14 +64,6 @@ namespace Org.OpenAPITools.Test.Model
// TODO unit test for the property 'Code' // TODO unit test for the property 'Code'
} }
/// <summary> /// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
/// <summary>
/// Test the property 'Message' /// Test the property 'Message'
/// </summary> /// </summary>
[Fact] [Fact]
@ -80,6 +71,14 @@ namespace Org.OpenAPITools.Test.Model
{ {
// TODO unit test for the property 'Message' // TODO unit test for the property 'Message'
} }
/// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
} }

View File

@ -18,7 +18,6 @@ using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model namespace Org.OpenAPITools.Test.Model
{ {

Some files were not shown because too many files have changed in this diff Show More