Merge remote-tracking branch 'origin/master' into okhttp-gson-next-gen-better-error

This commit is contained in:
William Cheng 2021-12-07 16:23:16 +08:00
commit fe64d88887
87 changed files with 9799 additions and 24 deletions

View File

@ -76,7 +76,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient, Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** |
@ -954,6 +954,7 @@ Here is a list of template creators:
* C# ASP.NET 5: @jimschubert [:heart:](https://www.patreon.com/jimschubert)
* C# ASP.NET Core 3.0: @A-Joshi
* C# APS.NET Core 3.1: @phatcher
* C# Azure functions: @Abrhm7786
* C# NancyFX: @mstefaniuk
* C++ (Qt5 QHttpEngine): @etherealjoy
* C++ Pistache: @sebymiano

View File

@ -0,0 +1,6 @@
generatorName: csharp-netcore-functions
outputDir: samples/client/petstore/csharp-netcore-functions
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore-functions
#additionalProperties:
# packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'

View File

@ -86,7 +86,7 @@ The following generators are available:
* [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md)
* [cpp-restbed-server](generators/cpp-restbed-server.md)
* [csharp-nancyfx](generators/csharp-nancyfx.md)
* [csharp-netcore-functions](generators/csharp-netcore-functions.md)
* [csharp-netcore-functions (beta)](generators/csharp-netcore-functions.md)
* [erlang-server](generators/erlang-server.md)
* [fsharp-functions (beta)](generators/fsharp-functions.md)
* [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md)

View File

@ -266,10 +266,10 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES,
CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC,
this.optionalEmitDefaultValuesFlag);
addSwitch(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION,
CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC,
this.conditionalSerialization);
CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC,
this.conditionalSerialization);
addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE,
CodegenConstants.OPTIONAL_PROJECT_FILE_DESC,
@ -588,7 +588,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
additionalProperties.put("multiTarget", true);
} else {
// just a single value
frameworks = new String [] {inputFramework};
frameworks = new String[]{inputFramework};
}
for (String framework : frameworks) {
@ -600,14 +600,14 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
}
if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) {
LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later.");
LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later.");
}
}
if (!strategyMatched) {
// throws exception if the input targetFramework is invalid
throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " +
framework + ". List of supported versions: " +
framework + ". List of supported versions: " +
frameworkStrategies.stream()
.map(p -> p.name)
.collect(Collectors.joining(", ")));
@ -634,7 +634,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
final AtomicReference<Boolean> excludeTests = new AtomicReference<>();
syncBooleanProperty(additionalProperties, CodegenConstants.EXCLUDE_TESTS, excludeTests::set, false);
syncStringProperty(additionalProperties, "clientPackage", (s) -> { }, clientPackage);
syncStringProperty(additionalProperties, "clientPackage", (s) -> {}, clientPackage);
syncStringProperty(additionalProperties, CodegenConstants.API_PACKAGE, this::setApiPackage, apiPackage);
syncStringProperty(additionalProperties, CodegenConstants.MODEL_PACKAGE, this::setModelPackage, modelPackage);
@ -669,7 +669,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
binRelativePath += "vendor";
additionalProperties.put("binRelativePath", binRelativePath);
if(HTTPCLIENT.equals(getLibrary())) {
if (HTTPCLIENT.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs"));
typeMapping.put("file", "FileParameter");
}
@ -682,10 +682,10 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
if(needsCustomHttpMethod) {
if (needsCustomHttpMethod) {
supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
}
if(needsUriBuilder) {
if (needsUriBuilder) {
supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs"));
}
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
@ -736,7 +736,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
this.optionalEmitDefaultValuesFlag = flag;
}
public void setConditionalSerialization(boolean flag){
public void setConditionalSerialization(boolean flag) {
this.conditionalSerialization = flag;
}
@ -771,8 +771,8 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen {
throw new IllegalArgumentException("Invalid .NET framework version: " +
dotnetFramework + ". List of supported versions: " +
frameworkStrategies.stream()
.map(p -> p.name)
.collect(Collectors.joining(", ")));
.map(p -> p.name)
.collect(Collectors.joining(", ")));
} else {
this.targetFramework = dotnetFramework;
}

View File

@ -1,3 +1,19 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
@ -11,10 +27,12 @@ import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen {
public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen {
public static final String PROJECT_NAME = "projectName";
final Logger LOGGER = LoggerFactory.getLogger(CsharpNetcoreFunctionsServerCodegen.class);
@ -33,6 +51,11 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli
public CsharpNetcoreFunctionsServerCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
outputFolder = "generated-code" + File.separator + "csharp";
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("functions.mustache", ".cs");
@ -42,7 +65,7 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli
String clientPackageDir = "generatedSrc/Client";
supportingFiles.add(new SupportingFile("README.mustache", "generatedSrc", "README.md"));
supportingFiles.add(new SupportingFile("project.mustache", "generatedSrc", "project.json"));
supportingFiles.add(new SupportingFile("IApiAccessor.mustache",
clientPackageDir, "IApiAccessor.cs"));
supportingFiles.add(new SupportingFile("Configuration.mustache",
@ -66,7 +89,7 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli
@Override
public String modelFileFolder() {
return outputFolder + File.separator + "generatedSrc" + File.separator + "Models";
return outputFolder + File.separator + "generatedSrc" + File.separator + "Models";
}
@Override

View File

@ -50,11 +50,17 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
return (TypeAdapter<T>) new TypeAdapter<{{classname}}>() {
@Override
public void write(JsonWriter out, {{classname}} value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
{{#anyOf}}
// check if the actual instance is of the type `{{.}}`
if (value.getActualInstance() instanceof {{.}}) {
JsonObject obj = adapter{{.}}.toJsonTree(({{.}})value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
{{/anyOf}}

View File

@ -50,11 +50,17 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
return (TypeAdapter<T>) new TypeAdapter<{{classname}}>() {
@Override
public void write(JsonWriter out, {{classname}} value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
{{#oneOf}}
// check if the actual instance is of the type `{{.}}`
if (value.getActualInstance() instanceof {{.}}) {
JsonObject obj = adapter{{.}}.toJsonTree(({{.}})value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
{{/oneOf}}

View File

@ -1888,6 +1888,11 @@ components:
type: string
pattern: /^[A-Z\s]*$/i
nullable: true
pineapple:
type: object
properties:
origin:
type: string
banana:
type: object
properties:
@ -1950,6 +1955,7 @@ components:
color:
type: string
anyOf:
- $ref: '#/components/schemas/pineapple'
- $ref: '#/components/schemas/apple'
- $ref: '#/components/schemas/banana'
additionalProperties: false

View File

@ -0,0 +1,362 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,51 @@
.gitignore
Docs/PetApi.md
Docs/StoreApi.md
Docs/UserApi.md
README.md
appveyor.yml
docs/ApiResponse.md
docs/Category.md
docs/Order.md
docs/Pet.md
docs/Tag.md
docs/User.md
generatedSrc/Client/ApiClient.cs
generatedSrc/Client/ApiException.cs
generatedSrc/Client/ApiResponse.cs
generatedSrc/Client/Configuration.cs
generatedSrc/Client/ExceptionFactory.cs
generatedSrc/Client/IApiAccessor.cs
generatedSrc/Client/OpenAPIDateConverter.cs
generatedSrc/Functions/PetApi.cs
generatedSrc/Functions/PetApi.cs
generatedSrc/Functions/StoreApi.cs
generatedSrc/Functions/StoreApi.cs
generatedSrc/Functions/UserApi.cs
generatedSrc/Functions/UserApi.cs
generatedSrc/Models/ApiResponse.cs
generatedSrc/Models/Category.cs
generatedSrc/Models/Order.cs
generatedSrc/Models/Pet.cs
generatedSrc/Models/Tag.cs
generatedSrc/Models/User.cs
generatedSrc/README.md
generatedSrc/project.json
git_push.sh
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs
src/Org.OpenAPITools/Client/GlobalConfiguration.cs
src/Org.OpenAPITools/Client/HttpMethod.cs
src/Org.OpenAPITools/Client/IApiAccessor.cs
src/Org.OpenAPITools/Client/IAsynchronousClient.cs
src/Org.OpenAPITools/Client/IReadableConfiguration.cs
src/Org.OpenAPITools/Client/ISynchronousClient.cs
src/Org.OpenAPITools/Client/Multimap.cs
src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs
src/Org.OpenAPITools/Client/RequestOptions.cs
src/Org.OpenAPITools/Client/RetryConfiguration.cs
src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs

View File

@ -0,0 +1 @@
5.3.1-SNAPSHOT

View File

@ -0,0 +1,159 @@
# Org.OpenAPITools - the C# library for the OpenAPI Petstore
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 1.0.0
- SDK version: 1.0.0
- Build package: org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen
<a name="frameworks-supported"></a>
## Frameworks supported
- .NET Core >=1.0
- .NET Framework >=4.6
- Mono/Xamarin >=vNext
<a name="dependencies"></a>
## Dependencies
- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later
- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later
- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later
- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later
The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages:
```
Install-Package RestSharp
Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
Install-Package System.ComponentModel.Annotations
```
NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742).
NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406).
<a name="installation"></a>
## Installation
Generate the DLL using your preferred tool (e.g. `dotnet build`)
Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces:
```csharp
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
```
<a name="usage"></a>
## Usage
To use the API client with a HTTP proxy, setup a `System.Net.WebProxy`
```csharp
Configuration c = new Configuration();
System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/");
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
c.Proxy = webProxy;
```
<a name="getting-started"></a>
## Getting Started
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class Example
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var pet = new Pet(); // Pet | Pet object that needs to be added to the store
try
{
// Add a new pet to the store
Pet result = apiInstance.AddPet(pet);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.AddPet: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
<a name="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet
*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user
*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user
*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name
*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system
*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user
<a name="documentation-for-models"></a>
## Documentation for Models
- [Models.ApiResponse](docs/ApiResponse.md)
- [Models.Category](docs/Category.md)
- [Models.Order](docs/Order.md)
- [Models.Pet](docs/Pet.md)
- [Models.Tag](docs/Tag.md)
- [Models.User](docs/User.md)
<a name="documentation-for-authorization"></a>
## Documentation for Authorization
<a name="api_key"></a>
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
<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

View File

@ -0,0 +1,156 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using Xunit;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Apis;
// uncomment below to import models
//using Org.OpenAPITools.Models;
namespace Org.OpenAPITools.Test.Api
{
/// <summary>
/// Class for testing PetApi
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the API endpoint.
/// </remarks>
public class PetApiTests : IDisposable
{
private PetApi instance;
public PetApiTests()
{
instance = new PetApi();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of PetApi
/// </summary>
[Fact]
public void InstanceTest()
{
// TODO uncomment below to test 'IsType' PetApi
//Assert.IsType<PetApi>(instance);
}
/// <summary>
/// Test AddPet
/// </summary>
[Fact]
public void AddPetTest()
{
// TODO uncomment below to test the method and replace null with proper value
//Pet pet = null;
//var response = instance.AddPet(pet);
//Assert.IsType<Pet>(response);
}
/// <summary>
/// Test DeletePet
/// </summary>
[Fact]
public void DeletePetTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long petId = null;
//string apiKey = null;
//instance.DeletePet(petId, apiKey);
}
/// <summary>
/// Test FindPetsByStatus
/// </summary>
[Fact]
public void FindPetsByStatusTest()
{
// TODO uncomment below to test the method and replace null with proper value
//List<string> status = null;
//var response = instance.FindPetsByStatus(status);
//Assert.IsType<List<Pet>>(response);
}
/// <summary>
/// Test FindPetsByTags
/// </summary>
[Fact]
public void FindPetsByTagsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//List<string> tags = null;
//var response = instance.FindPetsByTags(tags);
//Assert.IsType<List<Pet>>(response);
}
/// <summary>
/// Test GetPetById
/// </summary>
[Fact]
public void GetPetByIdTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long petId = null;
//var response = instance.GetPetById(petId);
//Assert.IsType<Pet>(response);
}
/// <summary>
/// Test UpdatePet
/// </summary>
[Fact]
public void UpdatePetTest()
{
// TODO uncomment below to test the method and replace null with proper value
//Pet pet = null;
//var response = instance.UpdatePet(pet);
//Assert.IsType<Pet>(response);
}
/// <summary>
/// Test UpdatePetWithForm
/// </summary>
[Fact]
public void UpdatePetWithFormTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long petId = null;
//string name = null;
//string status = null;
//instance.UpdatePetWithForm(petId, name, status);
}
/// <summary>
/// Test UploadFile
/// </summary>
[Fact]
public void UploadFileTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long petId = null;
//string additionalMetadata = null;
//System.IO.Stream file = null;
//var response = instance.UploadFile(petId, additionalMetadata, file);
//Assert.IsType<ApiResponse>(response);
}
}
}

View File

@ -0,0 +1,103 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using Xunit;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Apis;
// uncomment below to import models
//using Org.OpenAPITools.Models;
namespace Org.OpenAPITools.Test.Api
{
/// <summary>
/// Class for testing StoreApi
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the API endpoint.
/// </remarks>
public class StoreApiTests : IDisposable
{
private StoreApi instance;
public StoreApiTests()
{
instance = new StoreApi();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of StoreApi
/// </summary>
[Fact]
public void InstanceTest()
{
// TODO uncomment below to test 'IsType' StoreApi
//Assert.IsType<StoreApi>(instance);
}
/// <summary>
/// Test DeleteOrder
/// </summary>
[Fact]
public void DeleteOrderTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string orderId = null;
//instance.DeleteOrder(orderId);
}
/// <summary>
/// Test GetInventory
/// </summary>
[Fact]
public void GetInventoryTest()
{
// TODO uncomment below to test the method and replace null with proper value
//var response = instance.GetInventory();
//Assert.IsType<Dictionary<string, int>>(response);
}
/// <summary>
/// Test GetOrderById
/// </summary>
[Fact]
public void GetOrderByIdTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long orderId = null;
//var response = instance.GetOrderById(orderId);
//Assert.IsType<Order>(response);
}
/// <summary>
/// Test PlaceOrder
/// </summary>
[Fact]
public void PlaceOrderTest()
{
// TODO uncomment below to test the method and replace null with proper value
//Order order = null;
//var response = instance.PlaceOrder(order);
//Assert.IsType<Order>(response);
}
}
}

View File

@ -0,0 +1,148 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using Xunit;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Apis;
// uncomment below to import models
//using Org.OpenAPITools.Models;
namespace Org.OpenAPITools.Test.Api
{
/// <summary>
/// Class for testing UserApi
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the API endpoint.
/// </remarks>
public class UserApiTests : IDisposable
{
private UserApi instance;
public UserApiTests()
{
instance = new UserApi();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of UserApi
/// </summary>
[Fact]
public void InstanceTest()
{
// TODO uncomment below to test 'IsType' UserApi
//Assert.IsType<UserApi>(instance);
}
/// <summary>
/// Test CreateUser
/// </summary>
[Fact]
public void CreateUserTest()
{
// TODO uncomment below to test the method and replace null with proper value
//User user = null;
//instance.CreateUser(user);
}
/// <summary>
/// Test CreateUsersWithArrayInput
/// </summary>
[Fact]
public void CreateUsersWithArrayInputTest()
{
// TODO uncomment below to test the method and replace null with proper value
//List<User> user = null;
//instance.CreateUsersWithArrayInput(user);
}
/// <summary>
/// Test CreateUsersWithListInput
/// </summary>
[Fact]
public void CreateUsersWithListInputTest()
{
// TODO uncomment below to test the method and replace null with proper value
//List<User> user = null;
//instance.CreateUsersWithListInput(user);
}
/// <summary>
/// Test DeleteUser
/// </summary>
[Fact]
public void DeleteUserTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string username = null;
//instance.DeleteUser(username);
}
/// <summary>
/// Test GetUserByName
/// </summary>
[Fact]
public void GetUserByNameTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string username = null;
//var response = instance.GetUserByName(username);
//Assert.IsType<User>(response);
}
/// <summary>
/// Test LoginUser
/// </summary>
[Fact]
public void LoginUserTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string username = null;
//string password = null;
//var response = instance.LoginUser(username, password);
//Assert.IsType<string>(response);
}
/// <summary>
/// Test LogoutUser
/// </summary>
[Fact]
public void LogoutUserTest()
{
// TODO uncomment below to test the method and replace null with proper value
//instance.LogoutUser();
}
/// <summary>
/// Test UpdateUser
/// </summary>
[Fact]
public void UpdateUserTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string username = null;
//User user = null;
//instance.UpdateUser(username, user);
}
}
}

View File

@ -0,0 +1,9 @@
# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator)
#
image: Visual Studio 2019
clone_depth: 1
build_script:
- dotnet build -c Release
- dotnet test -c Release
after_build:
- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build

View File

@ -0,0 +1,13 @@
# Org.OpenAPITools.Models.ApiResponse
Describes the result of uploading an image resource
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Code** | **int** | | [optional]
**Type** | **string** | | [optional]
**Message** | **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)

View File

@ -0,0 +1,12 @@
# Org.OpenAPITools.Models.Category
A category for a pet
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**Name** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# Org.OpenAPITools.Models.Order
An order for a pets from the pet store
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**PetId** | **long** | | [optional]
**Quantity** | **int** | | [optional]
**ShipDate** | **DateTime** | | [optional]
**Status** | **string** | Order Status | [optional]
**Complete** | **bool** | | [optional] [default to false]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# Org.OpenAPITools.Models.Pet
A pet for sale in the pet store
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**Category** | [**Category**](Category.md) | | [optional]
**Name** | **string** | |
**PhotoUrls** | **List&lt;string&gt;** | |
**Tags** | [**List&lt;Tag&gt;**](Tag.md) | | [optional]
**Status** | **string** | pet status in the store | [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)

View File

@ -0,0 +1,616 @@
# Org.OpenAPITools.Apis.PetApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store
[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet
[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
<a name="addpet"></a>
# **AddPet**
> Pet AddPet (Pet pet)
Add a new pet to the store
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class AddPetExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var pet = new Pet(); // Pet | Pet object that needs to be added to the store
try
{
// Add a new pet to the store
Pet result = apiInstance.AddPet(pet);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.AddPet: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
[**Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **405** | Invalid input | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="deletepet"></a>
# **DeletePet**
> void DeletePet (long petId, string apiKey = null)
Deletes a pet
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class DeletePetExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var petId = 789; // long | Pet id to delete
var apiKey = apiKey_example; // string | (optional)
try
{
// Deletes a pet
apiInstance.DeletePet(petId, apiKey);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **long**| Pet id to delete |
**apiKey** | **string**| | [optional]
### Return type
void (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid pet value | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="findpetsbystatus"></a>
# **FindPetsByStatus**
> List&lt;Pet&gt; FindPetsByStatus (List<string> status)
Finds Pets by status
Multiple status values can be provided with comma separated strings
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class FindPetsByStatusExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var status = new List<string>(); // List<string> | Status values that need to be considered for filter
try
{
// Finds Pets by status
List<Pet> result = apiInstance.FindPetsByStatus(status);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**status** | [**List&lt;string&gt;**](string.md)| Status values that need to be considered for filter |
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid status value | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="findpetsbytags"></a>
# **FindPetsByTags**
> List&lt;Pet&gt; FindPetsByTags (List<string> tags)
Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class FindPetsByTagsExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var tags = new List<string>(); // List<string> | Tags to filter by
try
{
// Finds Pets by tags
List<Pet> result = apiInstance.FindPetsByTags(tags);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**tags** | [**List&lt;string&gt;**](string.md)| Tags to filter by |
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid tag value | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="getpetbyid"></a>
# **GetPetById**
> Pet GetPetById (long petId)
Find pet by ID
Returns a single pet
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class GetPetByIdExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new PetApi(config);
var petId = 789; // long | ID of pet to return
try
{
// Find pet by ID
Pet result = apiInstance.GetPetById(petId);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **long**| ID of pet to return |
### Return type
[**Pet**](Pet.md)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="updatepet"></a>
# **UpdatePet**
> Pet UpdatePet (Pet pet)
Update an existing pet
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class UpdatePetExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var pet = new Pet(); // Pet | Pet object that needs to be added to the store
try
{
// Update an existing pet
Pet result = apiInstance.UpdatePet(pet);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
[**Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
| **405** | Validation exception | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="updatepetwithform"></a>
# **UpdatePetWithForm**
> void UpdatePetWithForm (long petId, string name = null, string status = null)
Updates a pet in the store with form data
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class UpdatePetWithFormExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var petId = 789; // long | ID of pet that needs to be updated
var name = name_example; // string | Updated name of the pet (optional)
var status = status_example; // string | Updated status of the pet (optional)
try
{
// Updates a pet in the store with form data
apiInstance.UpdatePetWithForm(petId, name, status);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **long**| ID of pet that needs to be updated |
**name** | **string**| Updated name of the pet | [optional]
**status** | **string**| Updated status of the pet | [optional]
### Return type
void (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="uploadfile"></a>
# **UploadFile**
> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null)
uploads an image
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class UploadFileExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var petId = 789; // long | ID of pet to update
var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional)
var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional)
try
{
// uploads an image
ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **long**| ID of pet to update |
**additionalMetadata** | **string**| Additional data to pass to server | [optional]
**file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional]
### Return type
[**ApiResponse**](ApiResponse.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,298 @@
# Org.OpenAPITools.Apis.StoreApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet
<a name="deleteorder"></a>
# **DeleteOrder**
> void DeleteOrder (string orderId)
Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class DeleteOrderExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
var apiInstance = new StoreApi(config);
var orderId = orderId_example; // string | ID of the order that needs to be deleted
try
{
// Delete purchase order by ID
apiInstance.DeleteOrder(orderId);
}
catch (ApiException e)
{
Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderId** | **string**| ID of the order that needs to be deleted |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="getinventory"></a>
# **GetInventory**
> Dictionary&lt;string, int&gt; GetInventory ()
Returns pet inventories by status
Returns a map of status codes to quantities
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class GetInventoryExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new StoreApi(config);
try
{
// Returns pet inventories by status
Dictionary<string, int> result = apiInstance.GetInventory();
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
**Dictionary<string, int>**
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="getorderbyid"></a>
# **GetOrderById**
> Order GetOrderById (long orderId)
Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class GetOrderByIdExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
var apiInstance = new StoreApi(config);
var orderId = 789; // long | ID of pet that needs to be fetched
try
{
// Find purchase order by ID
Order result = apiInstance.GetOrderById(orderId);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderId** | **long**| ID of pet that needs to be fetched |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="placeorder"></a>
# **PlaceOrder**
> Order PlaceOrder (Order order)
Place an order for a pet
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class PlaceOrderExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
var apiInstance = new StoreApi(config);
var order = new Order(); // Order | order placed for purchasing the pet
try
{
// Place an order for a pet
Order result = apiInstance.PlaceOrder(order);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**order** | [**Order**](Order.md)| order placed for purchasing the pet |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Order | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,12 @@
# Org.OpenAPITools.Models.Tag
A tag for a pet
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**Name** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,18 @@
# Org.OpenAPITools.Models.User
A User who is purchasing from the pet store
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **long** | | [optional]
**Username** | **string** | | [optional]
**FirstName** | **string** | | [optional]
**LastName** | **string** | | [optional]
**Email** | **string** | | [optional]
**Password** | **string** | | [optional]
**Phone** | **string** | | [optional]
**UserStatus** | **int** | User Status | [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)

View File

@ -0,0 +1,603 @@
# Org.OpenAPITools.Apis.UserApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user
[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user
[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name
[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system
[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user
<a name="createuser"></a>
# **CreateUser**
> void CreateUser (User user)
Create user
This can only be done by the logged in user.
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class CreateUserExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
var user = new User(); // User | Created user object
try
{
// Create user
apiInstance.CreateUser(user);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**user** | [**User**](User.md)| Created user object |
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="createuserswitharrayinput"></a>
# **CreateUsersWithArrayInput**
> void CreateUsersWithArrayInput (List<User> user)
Creates list of users with given input array
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class CreateUsersWithArrayInputExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
var user = new List<User>(); // List<User> | List of user object
try
{
// Creates list of users with given input array
apiInstance.CreateUsersWithArrayInput(user);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**user** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="createuserswithlistinput"></a>
# **CreateUsersWithListInput**
> void CreateUsersWithListInput (List<User> user)
Creates list of users with given input array
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class CreateUsersWithListInputExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
var user = new List<User>(); // List<User> | List of user object
try
{
// Creates list of users with given input array
apiInstance.CreateUsersWithListInput(user);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**user** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="deleteuser"></a>
# **DeleteUser**
> void DeleteUser (string username)
Delete user
This can only be done by the logged in user.
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class DeleteUserExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
var username = username_example; // string | The name that needs to be deleted
try
{
// Delete user
apiInstance.DeleteUser(username);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **string**| The name that needs to be deleted |
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="getuserbyname"></a>
# **GetUserByName**
> User GetUserByName (string username)
Get user by user name
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class GetUserByNameExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
var apiInstance = new UserApi(config);
var username = username_example; // string | The name that needs to be fetched. Use user1 for testing.
try
{
// Get user by user name
User result = apiInstance.GetUserByName(username);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **string**| The name that needs to be fetched. Use user1 for testing. |
### Return type
[**User**](User.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="loginuser"></a>
# **LoginUser**
> string LoginUser (string username, string password)
Logs user into the system
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class LoginUserExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
var apiInstance = new UserApi(config);
var username = username_example; // string | The user name for login
var password = password_example; // string | The password for login in clear text
try
{
// Logs user into the system
string result = apiInstance.LoginUser(username, password);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **string**| The user name for login |
**password** | **string**| The password for login in clear text |
### Return type
**string**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the &#x60;api_key&#x60; apiKey authentication. <br> * X-Rate-Limit - calls per hour allowed by the user <br> * X-Expires-After - date in UTC when token expires <br> |
| **400** | Invalid username/password supplied | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="logoutuser"></a>
# **LogoutUser**
> void LogoutUser ()
Logs out current logged in user session
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class LogoutUserExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
try
{
// Logs out current logged in user session
apiInstance.LogoutUser();
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
<a name="updateuser"></a>
# **UpdateUser**
> void UpdateUser (string username, User user)
Updated user
This can only be done by the logged in user.
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class UpdateUserExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure API key authorization: api_key
config.AddApiKey("api_key", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// config.AddApiKeyPrefix("api_key", "Bearer");
var apiInstance = new UserApi(config);
var username = username_example; // string | name that need to be deleted
var user = new User(); // User | Updated user object
try
{
// Updated user
apiInstance.UpdateUser(username, user);
}
catch (ApiException e)
{
Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **string**| name that need to be deleted |
**user** | [**User**](User.md)| Updated user object |
### Return type
void (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid user supplied | - |
| **404** | User not found | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,860 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
public CustomJsonCodec(IReadableConfiguration configuration)
{
_configuration = configuration;
}
public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
{
_serializerSettings = serializerSettings;
_configuration = configuration;
}
/// <summary>
/// Serialize the object into a JSON string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>A JSON string.</returns>
public string Serialize(object obj)
{
if (obj != null && obj is Org.OpenAPITools.Models.AbstractOpenAPISchema)
{
// the object to be serialized is an oneOf/anyOf schema
return ((Org.OpenAPITools.Models.AbstractOpenAPISchema)obj).ToJson();
}
else
{
return JsonConvert.SerializeObject(obj, _serializerSettings);
}
}
public T Deserialize<T>(IRestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = response.RawBytes;
if (response.Headers != null)
{
var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath)
? Path.GetTempPath()
: _configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in response.Headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, bytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(bytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios),
/// encapsulating general REST accessor use cases.
/// </summary>
public partial class ApiClient : ISynchronousClient, IAsynchronousClient
{
private readonly string _baseUrl;
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer" /> object.
/// These settings can be adjusted to accomodate custom serialization rules.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// </summary>
public ApiClient()
{
_baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />
/// </summary>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <exception cref="ArgumentException"></exception>
public ApiClient(string basePath)
{
if (string.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
_baseUrl = basePath;
}
/// <summary>
/// Constructs the RestSharp version of an http method
/// </summary>
/// <param name="method">Swagger Client Custom HttpMethod</param>
/// <returns>RestSharp's HttpMethod instance.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private RestSharpMethod Method(HttpMethod method)
{
RestSharpMethod other;
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
}
return other;
}
/// <summary>
/// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
/// At this point, all information for querying the service is known. Here, it is simply
/// mapped into the RestSharp request.
/// </summary>
/// <param name="method">The http verb.</param>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>[private] A new RestRequest instance.</returns>
/// <exception cref="ArgumentNullException"></exception>
private RestRequest NewRequest(
HttpMethod method,
string path,
RequestOptions options,
IReadableConfiguration configuration)
{
if (path == null) throw new ArgumentNullException("path");
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null)
{
foreach (var pathParam in options.PathParameters)
{
request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
}
}
if (options.QueryParameters != null)
{
foreach (var queryParam in options.QueryParameters)
{
foreach (var value in queryParam.Value)
{
request.AddQueryParameter(queryParam.Key, value);
}
}
}
if (configuration.DefaultHeaders != null)
{
foreach (var headerParam in configuration.DefaultHeaders)
{
request.AddHeader(headerParam.Key, headerParam.Value);
}
}
if (options.HeaderParameters != null)
{
foreach (var headerParam in options.HeaderParameters)
{
foreach (var value in headerParam.Value)
{
request.AddHeader(headerParam.Key, value);
}
}
}
if (options.FormParameters != null)
{
foreach (var formParam in options.FormParameters)
{
request.AddParameter(formParam.Key, formParam.Value);
}
}
if (options.Data != null)
{
if (options.Data is Stream stream)
{
var contentType = "application/octet-stream";
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
contentType = contentTypes[0];
}
var bytes = ClientUtils.ReadAsBytes(stream);
request.AddParameter(contentType, bytes, ParameterType.RequestBody);
}
else
{
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
{
request.RequestFormat = DataFormat.Json;
}
else
{
// TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
}
}
else
{
// Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
request.RequestFormat = DataFormat.Json;
}
request.AddJsonBody(options.Data);
}
}
if (options.FileParameters != null)
{
foreach (var fileParam in options.FileParameters)
{
var bytes = ClientUtils.ReadAsBytes(fileParam.Value);
var fileStream = fileParam.Value as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()
};
if (response.Headers != null)
{
foreach (var responseHeader in response.Headers)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
{
transformed.Cookies.Add(
new Cookie(
responseCookies.Name,
responseCookies.Value,
responseCookies.Path,
responseCookies.Domain)
);
}
}
return transformed;
}
private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration)
{
RestClient client = new RestClient(_baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = client.Execute<T>(req);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
RestClient client = new RestClient(_baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
#region IAsynchronousClient
/// <summary>
/// Make a HTTP GET request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP POST request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PUT request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP DELETE request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP HEAD request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP OPTION request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PATCH request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken);
}
#endregion IAsynchronousClient
#region ISynchronousClient
/// <summary>
/// Make a HTTP GET request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config);
}
/// <summary>
/// Make a HTTP POST request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config);
}
/// <summary>
/// Make a HTTP PUT request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config);
}
/// <summary>
/// Make a HTTP DELETE request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config);
}
/// <summary>
/// Make a HTTP HEAD request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config);
}
/// <summary>
/// Make a HTTP OPTION request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config);
}
/// <summary>
/// Make a HTTP PATCH request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config);
}
#endregion ISynchronousClient
}
}

View File

@ -0,0 +1,68 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// API Exception
/// </summary>
public class ApiException : Exception
{
/// <summary>
/// Gets or sets the error code (HTTP status code)
/// </summary>
/// <value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary>
/// Gets or sets the error content (body json object)
/// </summary>
/// <value>The error content (Http response body).</value>
public object ErrorContent { get; private set; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
public ApiException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
public ApiException(int errorCode, string message) : base(message)
{
this.ErrorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
/// <param name="errorContent">Error content.</param>
/// <param name="headers">HTTP Headers.</param>
public ApiException(int errorCode, string message, object errorContent = null, Multimap<string, string> headers = null) : base(message)
{
this.ErrorCode = errorCode;
this.ErrorContent = errorContent;
this.Headers = headers;
}
}
}

View File

@ -0,0 +1,166 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Provides a non-generic contract for the ApiResponse wrapper.
/// </summary>
public interface IApiResponse
{
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
Type ResponseType { get; }
/// <summary>
/// The content of this response
/// </summary>
Object Content { get; }
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
List<Cookie> Cookies { get; set; }
/// <summary>
/// The raw content of this response
/// </summary>
string RawContent { get; }
}
/// <summary>
/// API Response
/// </summary>
public class ApiResponse<T> : IApiResponse
{
#region Properties
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets the data (parsed HTTP body)
/// </summary>
/// <value>The data.</value>
public T Data { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
public string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
public List<Cookie> Cookies { get; set; }
/// <summary>
/// The content of this response
/// </summary>
public Type ResponseType
{
get { return typeof(T); }
}
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
public object Content
{
get { return Data; }
}
/// <summary>
/// The raw content
/// </summary>
public string RawContent { get; }
#endregion Properties
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data, string rawContent)
{
StatusCode = statusCode;
Headers = headers;
Data = data;
RawContent = rawContent;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data) : this(statusCode, headers, data, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null)
{
}
#endregion Constructors
}
}

View File

@ -0,0 +1,515 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration : IReadableConfiguration
{
#region Constants
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Identifier for ISO 8601 DateTime Format
/// </summary>
/// <remarks>See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information.</remarks>
// ReSharper disable once InconsistentNaming
public const string ISO8601_DATETIME_FORMAT = "o";
#endregion Constants
#region Static Members
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
var status = (int)response.StatusCode;
if (status >= 400)
{
return new ApiException(status,
string.Format("Error calling {0}: {1}", methodName, response.RawContent),
response.RawContent, response.Headers);
}
return null;
};
#endregion Static Members
#region Private Members
/// <summary>
/// Defines the base path of the target API server.
/// Example: http://localhost:3000/v1/
/// </summary>
private string _basePath;
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// This is the key and value comprising the "secret" for acessing an API.
/// </summary>
/// <value>The API key.</value>
private IDictionary<string, string> _apiKey;
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
private IDictionary<string, string> _apiKeyPrefix;
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the servers defined in the OpenAPI spec.
/// </summary>
/// <value>The servers</value>
private IList<IReadOnlyDictionary<string, object>> _servers;
#endregion Private Members
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
BasePath = "http://petstore.swagger.io/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
ApiKeyPrefix = new ConcurrentDictionary<string, string>();
Servers = new List<IReadOnlyDictionary<string, object>>()
{
{
new Dictionary<string, object> {
{"url", "http://petstore.swagger.io/v2"},
{"description", "No description provided"},
}
}
};
// Setting Timeout has side effects (forces ApiClient creation).
Timeout = 100000;
}
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration(
IDictionary<string, string> defaultHeaders,
IDictionary<string, string> apiKey,
IDictionary<string, string> apiKeyPrefix,
string basePath = "http://petstore.swagger.io/v2") : this()
{
if (string.IsNullOrWhiteSpace(basePath))
throw new ArgumentException("The provided basePath is invalid.", "basePath");
if (defaultHeaders == null)
throw new ArgumentNullException("defaultHeaders");
if (apiKey == null)
throw new ArgumentNullException("apiKey");
if (apiKeyPrefix == null)
throw new ArgumentNullException("apiKeyPrefix");
BasePath = basePath;
foreach (var keyValuePair in defaultHeaders)
{
DefaultHeaders.Add(keyValuePair);
}
foreach (var keyValuePair in apiKey)
{
ApiKey.Add(keyValuePair);
}
foreach (var keyValuePair in apiKeyPrefix)
{
ApiKeyPrefix.Add(keyValuePair);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the base path for API access.
/// </summary>
public virtual string BasePath {
get { return _basePath; }
set { _basePath = value; }
}
/// <summary>
/// Gets or sets the default header.
/// </summary>
[Obsolete("Use DefaultHeaders instead.")]
public virtual IDictionary<string, string> DefaultHeader
{
get
{
return DefaultHeaders;
}
set
{
DefaultHeaders = value;
}
}
/// <summary>
/// Gets or sets the default headers.
/// </summary>
public virtual IDictionary<string, string> DefaultHeaders { get; set; }
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
public virtual int Timeout { get; set; }
/// <summary>
/// Gets or sets the proxy
/// </summary>
/// <value>Proxy.</value>
public virtual WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public virtual string UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public virtual string Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public virtual string Password { get; set; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix(string apiKeyIdentifier)
{
string apiKeyValue;
ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue);
string apiKeyPrefix;
if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix))
{
return apiKeyPrefix + " " + apiKeyValue;
}
return apiKeyValue;
}
/// <summary>
/// Gets or sets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
public X509CertificateCollection ClientCertificates { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
///
/// This helper property simplifies code generation.
/// </summary>
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public virtual string TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (string.IsNullOrEmpty(value))
{
_tempFolderPath = Path.GetTempPath();
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
{
_tempFolderPath = value;
}
else
{
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
}
/// <summary>
/// Gets or sets the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public virtual string DateTimeFormat
{
get { return _dateTimeFormat; }
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
///
/// Whatever you set here will be prepended to the value defined in AddApiKey.
///
/// An example invocation here might be:
/// <example>
/// ApiKeyPrefix["Authorization"] = "Bearer";
/// </example>
/// … where ApiKey["Authorization"] would then be used to set the value of your bearer token.
///
/// <remarks>
/// OAuth2 workflows should set tokens via AccessToken.
/// </remarks>
/// </summary>
/// <value>The prefix of the API key.</value>
public virtual IDictionary<string, string> ApiKeyPrefix
{
get { return _apiKeyPrefix; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKeyPrefix collection may not be null.");
}
_apiKeyPrefix = value;
}
}
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public virtual IDictionary<string, string> ApiKey
{
get { return _apiKey; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKey collection may not be null.");
}
_apiKey = value;
}
}
/// <summary>
/// Gets or sets the servers.
/// </summary>
/// <value>The servers.</value>
public virtual IList<IReadOnlyDictionary<string, object>> Servers
{
get { return _servers; }
set
{
if (value == null)
{
throw new InvalidOperationException("Servers may not be null.");
}
_servers = value;
}
}
/// <summary>
/// Returns URL based on server settings without providing values
/// for the variables
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index)
{
return GetServerUrl(index, null);
}
/// <summary>
/// Returns URL based on server settings.
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index, Dictionary<string, string> inputVariables)
{
if (index < 0 || index >= Servers.Count)
{
throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}.");
}
if (inputVariables == null)
{
inputVariables = new Dictionary<string, string>();
}
IReadOnlyDictionary<string, object> server = Servers[index];
string url = (string)server["url"];
// go through variable and assign a value
foreach (KeyValuePair<string, object> variable in (IReadOnlyDictionary<string, object>)server["variables"])
{
IReadOnlyDictionary<string, object> serverVariables = (IReadOnlyDictionary<string, object>)(variable.Value);
if (inputVariables.ContainsKey(variable.Key))
{
if (((List<string>)serverVariables["enum_values"]).Contains(inputVariables[variable.Key]))
{
url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]);
}
else
{
throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List<string>)serverVariables["enum_values"]}");
}
}
else
{
// use defualt value
url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]);
}
}
return url;
}
#endregion Properties
#region Methods
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static string ToDebugReport()
{
string report = "C# SDK (Org.OpenAPITools) Debug Report:\n";
report += " OS: " + System.Environment.OSVersion + "\n";
report += " .NET Framework Version: " + System.Environment.Version + "\n";
report += " Version of the API: 1.0.0\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
/// <summary>
/// Add Api Key Header.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
/// <returns></returns>
public void AddApiKey(string key, string value)
{
ApiKey[key] = value;
}
/// <summary>
/// Sets the API key prefix.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
public void AddApiKeyPrefix(string key, string value)
{
ApiKeyPrefix[key] = value;
}
#endregion Methods
#region Static Members
/// <summary>
/// Merge configurations.
/// </summary>
/// <param name="first">First configuration.</param>
/// <param name="second">Second configuration.</param>
/// <return>Merged configuration.</return>
public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second)
{
if (second == null) return first ?? GlobalConfiguration.Instance;
Dictionary<string, string> apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value;
foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value;
foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value;
var config = new Configuration
{
ApiKey = apiKey,
ApiKeyPrefix = apiKeyPrefix,
DefaultHeaders = defaultHeaders,
BasePath = second.BasePath ?? first.BasePath,
Timeout = second.Timeout,
Proxy = second.Proxy ?? first.Proxy,
UserAgent = second.UserAgent ?? first.UserAgent,
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat
};
return config;
}
#endregion Static Members
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// A delegate to ExceptionFactory method
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="response">Response</param>
/// <returns>Exceptions</returns>
public delegate Exception ExceptionFactory(string methodName, IApiResponse response);
}

View File

@ -0,0 +1,37 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents configuration aspects required to interact with the API endpoints.
/// </summary>
public interface IApiAccessor
{
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
string GetBasePath();
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
ExceptionFactory ExceptionFactory { get; set; }
}
}

View File

@ -0,0 +1,29 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json.Converters;
namespace Org.OpenAPITools.Client
{
/// <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>
public class OpenAPIDateConverter : IsoDateTimeConverter
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenAPIDateConverter" /> class.
/// </summary>
public OpenAPIDateConverter()
{
// full-date = date-fullyear "-" date-month "-" date-mday
DateTimeFormat = "yyyy-MM-dd";
}
}
}

View File

@ -0,0 +1,104 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace Org.OpenAPITools.Apis
{
public partial class PetApi
{
[FunctionName("PetApi_AddPet")]
public async Task<IActionResult> _AddPet([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("AddPet");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_DeletePet")]
public async Task<IActionResult> _DeletePet([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId)
{
var method = this.GetType().GetMethod("DeletePet");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_FindPetsByStatus")]
public async Task<IActionResult> _FindPetsByStatus([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/findByStatus")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("FindPetsByStatus");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_FindPetsByTags")]
public async Task<IActionResult> _FindPetsByTags([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/findByTags")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("FindPetsByTags");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_GetPetById")]
public async Task<IActionResult> _GetPetById([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId)
{
var method = this.GetType().GetMethod("GetPetById");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_UpdatePet")]
public async Task<IActionResult> _UpdatePet([HttpTrigger(AuthorizationLevel.Anonymous, "PUT", Route = "/pet")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("UpdatePet");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_UpdatePetWithForm")]
public async Task<IActionResult> _UpdatePetWithForm([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId)
{
var method = this.GetType().GetMethod("UpdatePetWithForm");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("PetApi_UploadFile")]
public async Task<IActionResult> _UploadFile([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet/{petId}/uploadImage")]HttpRequest req, ExecutionContext context, long petId)
{
var method = this.GetType().GetMethod("UploadFile");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
}
}

View File

@ -0,0 +1,64 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace Org.OpenAPITools.Apis
{
public partial class StoreApi
{
[FunctionName("StoreApi_DeleteOrder")]
public async Task<IActionResult> _DeleteOrder([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/store/order/{orderId}")]HttpRequest req, ExecutionContext context, string orderId)
{
var method = this.GetType().GetMethod("DeleteOrder");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("StoreApi_GetInventory")]
public async Task<IActionResult> _GetInventory([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/store/inventory")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("GetInventory");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("StoreApi_GetOrderById")]
public async Task<IActionResult> _GetOrderById([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/store/order/{orderId}")]HttpRequest req, ExecutionContext context, [Range(1, 5)]long orderId)
{
var method = this.GetType().GetMethod("GetOrderById");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("StoreApi_PlaceOrder")]
public async Task<IActionResult> _PlaceOrder([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/store/order")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("PlaceOrder");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
}
}

View File

@ -0,0 +1,104 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace Org.OpenAPITools.Apis
{
public partial class UserApi
{
[FunctionName("UserApi_CreateUser")]
public async Task<IActionResult> _CreateUser([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("CreateUser");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_CreateUsersWithArrayInput")]
public async Task<IActionResult> _CreateUsersWithArrayInput([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user/createWithArray")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("CreateUsersWithArrayInput");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_CreateUsersWithListInput")]
public async Task<IActionResult> _CreateUsersWithListInput([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user/createWithList")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("CreateUsersWithListInput");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_DeleteUser")]
public async Task<IActionResult> _DeleteUser([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username)
{
var method = this.GetType().GetMethod("DeleteUser");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_GetUserByName")]
public async Task<IActionResult> _GetUserByName([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username)
{
var method = this.GetType().GetMethod("GetUserByName");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_LoginUser")]
public async Task<IActionResult> _LoginUser([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/login")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("LoginUser");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_LogoutUser")]
public async Task<IActionResult> _LogoutUser([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/logout")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("LogoutUser");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("UserApi_UpdateUser")]
public async Task<IActionResult> _UpdateUser([HttpTrigger(AuthorizationLevel.Anonymous, "PUT", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username)
{
var method = this.GetType().GetMethod("UpdateUser");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
}
}

View File

@ -0,0 +1,155 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// Describes the result of uploading an image resource
/// </summary>
[DataContract(Name = "ApiResponse")]
public partial class ApiResponse : IEquatable<ApiResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse" /> class.
/// </summary>
/// <param name="code">code.</param>
/// <param name="type">type.</param>
/// <param name="message">message.</param>
public ApiResponse(int code = default(int), string type = default(string), string message = default(string))
{
this.Code = code;
this.Type = type;
this.Message = message;
}
/// <summary>
/// Gets or Sets Code
/// </summary>
[DataMember(Name = "code", EmitDefaultValue = false)]
public int Code { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name = "type", EmitDefaultValue = false)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets Message
/// </summary>
[DataMember(Name = "message", EmitDefaultValue = false)]
public string Message { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ApiResponse {\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ApiResponse);
}
/// <summary>
/// Returns true if ApiResponse instances are equal
/// </summary>
/// <param name="input">Instance of ApiResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ApiResponse input)
{
if (input == null)
return false;
return
(
this.Code == input.Code ||
this.Code.Equals(input.Code)
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Code.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}

View File

@ -0,0 +1,146 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// A category for a pet
/// </summary>
[DataContract(Name = "Category")]
public partial class Category : IEquatable<Category>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Category" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="name">name.</param>
public Category(long id = default(long), string name = default(string))
{
this.Id = id;
this.Name = name;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public long Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Category {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Category);
}
/// <summary>
/// Returns true if Category instances are equal
/// </summary>
/// <param name="input">Instance of Category to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Category input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Name (string) pattern
Regex regexName = new Regex(@"^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", RegexOptions.CultureInvariant);
if (false == regexName.Match(this.Name).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, must match a pattern of " + regexName, new [] { "Name" });
}
yield break;
}
}
}

View File

@ -0,0 +1,223 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// An order for a pets from the pet store
/// </summary>
[DataContract(Name = "Order")]
public partial class Order : IEquatable<Order>, IValidatableObject
{
/// <summary>
/// Order Status
/// </summary>
/// <value>Order Status</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Placed for value: placed
/// </summary>
[EnumMember(Value = "placed")]
Placed = 1,
/// <summary>
/// Enum Approved for value: approved
/// </summary>
[EnumMember(Value = "approved")]
Approved = 2,
/// <summary>
/// Enum Delivered for value: delivered
/// </summary>
[EnumMember(Value = "delivered")]
Delivered = 3
}
/// <summary>
/// Order Status
/// </summary>
/// <value>Order Status</value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Order" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="petId">petId.</param>
/// <param name="quantity">quantity.</param>
/// <param name="shipDate">shipDate.</param>
/// <param name="status">Order Status.</param>
/// <param name="complete">complete (default to false).</param>
public Order(long id = default(long), long petId = default(long), int quantity = default(int), DateTime shipDate = default(DateTime), StatusEnum? status = default(StatusEnum?), bool complete = false)
{
this.Id = id;
this.PetId = petId;
this.Quantity = quantity;
this.ShipDate = shipDate;
this.Status = status;
this.Complete = complete;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public long Id { get; set; }
/// <summary>
/// Gets or Sets PetId
/// </summary>
[DataMember(Name = "petId", EmitDefaultValue = false)]
public long PetId { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name = "quantity", EmitDefaultValue = false)]
public int Quantity { get; set; }
/// <summary>
/// Gets or Sets ShipDate
/// </summary>
[DataMember(Name = "shipDate", EmitDefaultValue = false)]
public DateTime ShipDate { get; set; }
/// <summary>
/// Gets or Sets Complete
/// </summary>
[DataMember(Name = "complete", EmitDefaultValue = true)]
public bool Complete { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Order {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" PetId: ").Append(PetId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" ShipDate: ").Append(ShipDate).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Complete: ").Append(Complete).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Order);
}
/// <summary>
/// Returns true if Order instances are equal
/// </summary>
/// <param name="input">Instance of Order to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Order input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.PetId == input.PetId ||
this.PetId.Equals(input.PetId)
) &&
(
this.Quantity == input.Quantity ||
this.Quantity.Equals(input.Quantity)
) &&
(
this.ShipDate == input.ShipDate ||
(this.ShipDate != null &&
this.ShipDate.Equals(input.ShipDate))
) &&
(
this.Status == input.Status ||
this.Status.Equals(input.Status)
) &&
(
this.Complete == input.Complete ||
this.Complete.Equals(input.Complete)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Id.GetHashCode();
hashCode = hashCode * 59 + this.PetId.GetHashCode();
hashCode = hashCode * 59 + this.Quantity.GetHashCode();
if (this.ShipDate != null)
hashCode = hashCode * 59 + this.ShipDate.GetHashCode();
hashCode = hashCode * 59 + this.Status.GetHashCode();
hashCode = hashCode * 59 + this.Complete.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}

View File

@ -0,0 +1,238 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// A pet for sale in the pet store
/// </summary>
[DataContract(Name = "Pet")]
public partial class Pet : IEquatable<Pet>, IValidatableObject
{
/// <summary>
/// pet status in the store
/// </summary>
/// <value>pet status in the store</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Available for value: available
/// </summary>
[EnumMember(Value = "available")]
Available = 1,
/// <summary>
/// Enum Pending for value: pending
/// </summary>
[EnumMember(Value = "pending")]
Pending = 2,
/// <summary>
/// Enum Sold for value: sold
/// </summary>
[EnumMember(Value = "sold")]
Sold = 3
}
/// <summary>
/// pet status in the store
/// </summary>
/// <value>pet status in the store</value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Pet" /> class.
/// </summary>
[JsonConstructorAttribute]
protected Pet() { }
/// <summary>
/// Initializes a new instance of the <see cref="Pet" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="category">category.</param>
/// <param name="name">name (required).</param>
/// <param name="photoUrls">photoUrls (required).</param>
/// <param name="tags">tags.</param>
/// <param name="status">pet status in the store.</param>
public Pet(long id = default(long), Category category = default(Category), string name = default(string), List<string> photoUrls = default(List<string>), List<Tag> tags = default(List<Tag>), StatusEnum? status = default(StatusEnum?))
{
// to ensure "name" is required (not null)
this.Name = name ?? throw new ArgumentNullException("name is a required property for Pet and cannot be null");
// to ensure "photoUrls" is required (not null)
this.PhotoUrls = photoUrls ?? throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null");
this.Id = id;
this.Category = category;
this.Tags = tags;
this.Status = status;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public long Id { get; set; }
/// <summary>
/// Gets or Sets Category
/// </summary>
[DataMember(Name = "category", EmitDefaultValue = false)]
public Category Category { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets PhotoUrls
/// </summary>
[DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)]
public List<string> PhotoUrls { get; set; }
/// <summary>
/// Gets or Sets Tags
/// </summary>
[DataMember(Name = "tags", EmitDefaultValue = false)]
public List<Tag> Tags { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Pet {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Category: ").Append(Category).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n");
sb.Append(" Tags: ").Append(Tags).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Pet);
}
/// <summary>
/// Returns true if Pet instances are equal
/// </summary>
/// <param name="input">Instance of Pet to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Pet input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.Category == input.Category ||
(this.Category != null &&
this.Category.Equals(input.Category))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.PhotoUrls == input.PhotoUrls ||
this.PhotoUrls != null &&
input.PhotoUrls != null &&
this.PhotoUrls.SequenceEqual(input.PhotoUrls)
) &&
(
this.Tags == input.Tags ||
this.Tags != null &&
input.Tags != null &&
this.Tags.SequenceEqual(input.Tags)
) &&
(
this.Status == input.Status ||
this.Status.Equals(input.Status)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Category != null)
hashCode = hashCode * 59 + this.Category.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.PhotoUrls != null)
hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode();
if (this.Tags != null)
hashCode = hashCode * 59 + this.Tags.GetHashCode();
hashCode = hashCode * 59 + this.Status.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}

View File

@ -0,0 +1,139 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// A tag for a pet
/// </summary>
[DataContract(Name = "Tag")]
public partial class Tag : IEquatable<Tag>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Tag" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="name">name.</param>
public Tag(long id = default(long), string name = default(string))
{
this.Id = id;
this.Name = name;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public long Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Tag {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Tag);
}
/// <summary>
/// Returns true if Tag instances are equal
/// </summary>
/// <param name="input">Instance of Tag to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Tag input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}

View File

@ -0,0 +1,234 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// A User who is purchasing from the pet store
/// </summary>
[DataContract(Name = "User")]
public partial class User : IEquatable<User>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="User" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="username">username.</param>
/// <param name="firstName">firstName.</param>
/// <param name="lastName">lastName.</param>
/// <param name="email">email.</param>
/// <param name="password">password.</param>
/// <param name="phone">phone.</param>
/// <param name="userStatus">User Status.</param>
public User(long id = default(long), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int userStatus = default(int))
{
this.Id = id;
this.Username = username;
this.FirstName = firstName;
this.LastName = lastName;
this.Email = email;
this.Password = password;
this.Phone = phone;
this.UserStatus = userStatus;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public long Id { get; set; }
/// <summary>
/// Gets or Sets Username
/// </summary>
[DataMember(Name = "username", EmitDefaultValue = false)]
public string Username { get; set; }
/// <summary>
/// Gets or Sets FirstName
/// </summary>
[DataMember(Name = "firstName", EmitDefaultValue = false)]
public string FirstName { get; set; }
/// <summary>
/// Gets or Sets LastName
/// </summary>
[DataMember(Name = "lastName", EmitDefaultValue = false)]
public string LastName { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name = "email", EmitDefaultValue = false)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Password
/// </summary>
[DataMember(Name = "password", EmitDefaultValue = false)]
public string Password { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name = "phone", EmitDefaultValue = false)]
public string Phone { get; set; }
/// <summary>
/// User Status
/// </summary>
/// <value>User Status</value>
[DataMember(Name = "userStatus", EmitDefaultValue = false)]
public int UserStatus { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class User {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" UserStatus: ").Append(UserStatus).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as User);
}
/// <summary>
/// Returns true if User instances are equal
/// </summary>
/// <param name="input">Instance of User to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(User input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.Username == input.Username ||
(this.Username != null &&
this.Username.Equals(input.Username))
) &&
(
this.FirstName == input.FirstName ||
(this.FirstName != null &&
this.FirstName.Equals(input.FirstName))
) &&
(
this.LastName == input.LastName ||
(this.LastName != null &&
this.LastName.Equals(input.LastName))
) &&
(
this.Email == input.Email ||
(this.Email != null &&
this.Email.Equals(input.Email))
) &&
(
this.Password == input.Password ||
(this.Password != null &&
this.Password.Equals(input.Password))
) &&
(
this.Phone == input.Phone ||
(this.Phone != null &&
this.Phone.Equals(input.Phone))
) &&
(
this.UserStatus == input.UserStatus ||
this.UserStatus.Equals(input.UserStatus)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Username != null)
hashCode = hashCode * 59 + this.Username.GetHashCode();
if (this.FirstName != null)
hashCode = hashCode * 59 + this.FirstName.GetHashCode();
if (this.LastName != null)
hashCode = hashCode * 59 + this.LastName.GetHashCode();
if (this.Email != null)
hashCode = hashCode * 59 + this.Email.GetHashCode();
if (this.Password != null)
hashCode = hashCode * 59 + this.Password.GetHashCode();
if (this.Phone != null)
hashCode = hashCode * 59 + this.Phone.GetHashCode();
hashCode = hashCode * 59 + this.UserStatus.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}

View File

@ -0,0 +1,159 @@
# Org.OpenAPITools - the C# library for the OpenAPI Petstore
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 1.0.0
- SDK version: 1.0.0
- Build package: org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen
<a name="frameworks-supported"></a>
## Frameworks supported
- .NET Core >=1.0
- .NET Framework >=4.6
- Mono/Xamarin >=vNext
<a name="dependencies"></a>
## Dependencies
- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later
- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later
- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later
- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later
The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages:
```
Install-Package RestSharp
Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
Install-Package System.ComponentModel.Annotations
```
NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742).
NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406).
<a name="installation"></a>
## Installation
Generate the DLL using your preferred tool (e.g. `dotnet build`)
Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces:
```csharp
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
```
<a name="usage"></a>
## Usage
To use the API client with a HTTP proxy, setup a `System.Net.WebProxy`
```csharp
Configuration c = new Configuration();
System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/");
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
c.Proxy = webProxy;
```
<a name="getting-started"></a>
## Getting Started
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Models;
namespace Example
{
public class Example
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://petstore.swagger.io/v2";
// Configure OAuth2 access token for authorization: petstore_auth
config.AccessToken = "YOUR_ACCESS_TOKEN";
var apiInstance = new PetApi(config);
var pet = new Pet(); // Pet | Pet object that needs to be added to the store
try
{
// Add a new pet to the store
Pet result = apiInstance.AddPet(pet);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling PetApi.AddPet: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
<a name="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet
*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user
*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user
*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name
*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system
*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user
<a name="documentation-for-models"></a>
## Documentation for Models
- [Models.ApiResponse](docs/ApiResponse.md)
- [Models.Category](docs/Category.md)
- [Models.Order](docs/Order.md)
- [Models.Pet](docs/Pet.md)
- [Models.Tag](docs/Tag.md)
- [Models.User](docs/User.md)
<a name="documentation-for-authorization"></a>
## Documentation for Authorization
<a name="api_key"></a>
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
<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

View File

@ -0,0 +1,12 @@
{
"supports": {},
"dependencies": {
"FubarCoder.RestSharp.Portable.Core": "4.0.7",
"FubarCoder.RestSharp.Portable.HttpClient": "4.0.7",
"Newtonsoft.Json": "10.0.3",
"JsonSubTypes": "1.2.0"
},
"frameworks": {
"netstandard1.3": {}
}
}

View File

@ -0,0 +1,58 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,86 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing ApiResponse
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class ApiResponseTests : IDisposable
{
// TODO uncomment below to declare an instance variable for ApiResponse
//private ApiResponse instance;
public ApiResponseTests()
{
// TODO uncomment below to create an instance of ApiResponse
//instance = new ApiResponse();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of ApiResponse
/// </summary>
[Fact]
public void ApiResponseInstanceTest()
{
// TODO uncomment below to test "IsType" ApiResponse
//Assert.IsType<ApiResponse>(instance);
}
/// <summary>
/// Test the property 'Code'
/// </summary>
[Fact]
public void CodeTest()
{
// TODO unit test for the property 'Code'
}
/// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
/// <summary>
/// Test the property 'Message'
/// </summary>
[Fact]
public void MessageTest()
{
// TODO unit test for the property 'Message'
}
}
}

View File

@ -0,0 +1,78 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing Category
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class CategoryTests : IDisposable
{
// TODO uncomment below to declare an instance variable for Category
//private Category instance;
public CategoryTests()
{
// TODO uncomment below to create an instance of Category
//instance = new Category();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of Category
/// </summary>
[Fact]
public void CategoryInstanceTest()
{
// TODO uncomment below to test "IsType" Category
//Assert.IsType<Category>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Fact]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
}
}

View File

@ -0,0 +1,110 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing Order
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class OrderTests : IDisposable
{
// TODO uncomment below to declare an instance variable for Order
//private Order instance;
public OrderTests()
{
// TODO uncomment below to create an instance of Order
//instance = new Order();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of Order
/// </summary>
[Fact]
public void OrderInstanceTest()
{
// TODO uncomment below to test "IsType" Order
//Assert.IsType<Order>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'PetId'
/// </summary>
[Fact]
public void PetIdTest()
{
// TODO unit test for the property 'PetId'
}
/// <summary>
/// Test the property 'Quantity'
/// </summary>
[Fact]
public void QuantityTest()
{
// TODO unit test for the property 'Quantity'
}
/// <summary>
/// Test the property 'ShipDate'
/// </summary>
[Fact]
public void ShipDateTest()
{
// TODO unit test for the property 'ShipDate'
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Fact]
public void StatusTest()
{
// TODO unit test for the property 'Status'
}
/// <summary>
/// Test the property 'Complete'
/// </summary>
[Fact]
public void CompleteTest()
{
// TODO unit test for the property 'Complete'
}
}
}

View File

@ -0,0 +1,110 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing Pet
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class PetTests : IDisposable
{
// TODO uncomment below to declare an instance variable for Pet
//private Pet instance;
public PetTests()
{
// TODO uncomment below to create an instance of Pet
//instance = new Pet();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of Pet
/// </summary>
[Fact]
public void PetInstanceTest()
{
// TODO uncomment below to test "IsType" Pet
//Assert.IsType<Pet>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Category'
/// </summary>
[Fact]
public void CategoryTest()
{
// TODO unit test for the property 'Category'
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Fact]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
/// <summary>
/// Test the property 'PhotoUrls'
/// </summary>
[Fact]
public void PhotoUrlsTest()
{
// TODO unit test for the property 'PhotoUrls'
}
/// <summary>
/// Test the property 'Tags'
/// </summary>
[Fact]
public void TagsTest()
{
// TODO unit test for the property 'Tags'
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Fact]
public void StatusTest()
{
// TODO unit test for the property 'Status'
}
}
}

View File

@ -0,0 +1,78 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing Tag
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class TagTests : IDisposable
{
// TODO uncomment below to declare an instance variable for Tag
//private Tag instance;
public TagTests()
{
// TODO uncomment below to create an instance of Tag
//instance = new Tag();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of Tag
/// </summary>
[Fact]
public void TagInstanceTest()
{
// TODO uncomment below to test "IsType" Tag
//Assert.IsType<Tag>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Fact]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
}
}

View File

@ -0,0 +1,126 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Apis;
using Org.OpenAPITools.Models;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing User
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class UserTests : IDisposable
{
// TODO uncomment below to declare an instance variable for User
//private User instance;
public UserTests()
{
// TODO uncomment below to create an instance of User
//instance = new User();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of User
/// </summary>
[Fact]
public void UserInstanceTest()
{
// TODO uncomment below to test "IsType" User
//Assert.IsType<User>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Username'
/// </summary>
[Fact]
public void UsernameTest()
{
// TODO unit test for the property 'Username'
}
/// <summary>
/// Test the property 'FirstName'
/// </summary>
[Fact]
public void FirstNameTest()
{
// TODO unit test for the property 'FirstName'
}
/// <summary>
/// Test the property 'LastName'
/// </summary>
[Fact]
public void LastNameTest()
{
// TODO unit test for the property 'LastName'
}
/// <summary>
/// Test the property 'Email'
/// </summary>
[Fact]
public void EmailTest()
{
// TODO unit test for the property 'Email'
}
/// <summary>
/// Test the property 'Password'
/// </summary>
[Fact]
public void PasswordTest()
{
// TODO unit test for the property 'Password'
}
/// <summary>
/// Test the property 'Phone'
/// </summary>
[Fact]
public void PhoneTest()
{
// TODO unit test for the property 'Phone'
}
/// <summary>
/// Test the property 'UserStatus'
/// </summary>
[Fact]
public void UserStatusTest()
{
// TODO unit test for the property 'UserStatus'
}
}
}

View File

@ -0,0 +1,860 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
public CustomJsonCodec(IReadableConfiguration configuration)
{
_configuration = configuration;
}
public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
{
_serializerSettings = serializerSettings;
_configuration = configuration;
}
/// <summary>
/// Serialize the object into a JSON string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>A JSON string.</returns>
public string Serialize(object obj)
{
if (obj != null && obj is Org.OpenAPITools.Models.AbstractOpenAPISchema)
{
// the object to be serialized is an oneOf/anyOf schema
return ((Org.OpenAPITools.Models.AbstractOpenAPISchema)obj).ToJson();
}
else
{
return JsonConvert.SerializeObject(obj, _serializerSettings);
}
}
public T Deserialize<T>(IRestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = response.RawBytes;
if (response.Headers != null)
{
var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath)
? Path.GetTempPath()
: _configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in response.Headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, bytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(bytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios),
/// encapsulating general REST accessor use cases.
/// </summary>
public partial class ApiClient : ISynchronousClient, IAsynchronousClient
{
private readonly string _baseUrl;
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer" /> object.
/// These settings can be adjusted to accomodate custom serialization rules.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// </summary>
public ApiClient()
{
_baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />
/// </summary>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <exception cref="ArgumentException"></exception>
public ApiClient(string basePath)
{
if (string.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
_baseUrl = basePath;
}
/// <summary>
/// Constructs the RestSharp version of an http method
/// </summary>
/// <param name="method">Swagger Client Custom HttpMethod</param>
/// <returns>RestSharp's HttpMethod instance.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private RestSharpMethod Method(HttpMethod method)
{
RestSharpMethod other;
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
}
return other;
}
/// <summary>
/// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
/// At this point, all information for querying the service is known. Here, it is simply
/// mapped into the RestSharp request.
/// </summary>
/// <param name="method">The http verb.</param>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>[private] A new RestRequest instance.</returns>
/// <exception cref="ArgumentNullException"></exception>
private RestRequest NewRequest(
HttpMethod method,
string path,
RequestOptions options,
IReadableConfiguration configuration)
{
if (path == null) throw new ArgumentNullException("path");
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null)
{
foreach (var pathParam in options.PathParameters)
{
request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
}
}
if (options.QueryParameters != null)
{
foreach (var queryParam in options.QueryParameters)
{
foreach (var value in queryParam.Value)
{
request.AddQueryParameter(queryParam.Key, value);
}
}
}
if (configuration.DefaultHeaders != null)
{
foreach (var headerParam in configuration.DefaultHeaders)
{
request.AddHeader(headerParam.Key, headerParam.Value);
}
}
if (options.HeaderParameters != null)
{
foreach (var headerParam in options.HeaderParameters)
{
foreach (var value in headerParam.Value)
{
request.AddHeader(headerParam.Key, value);
}
}
}
if (options.FormParameters != null)
{
foreach (var formParam in options.FormParameters)
{
request.AddParameter(formParam.Key, formParam.Value);
}
}
if (options.Data != null)
{
if (options.Data is Stream stream)
{
var contentType = "application/octet-stream";
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
contentType = contentTypes[0];
}
var bytes = ClientUtils.ReadAsBytes(stream);
request.AddParameter(contentType, bytes, ParameterType.RequestBody);
}
else
{
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
{
request.RequestFormat = DataFormat.Json;
}
else
{
// TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
}
}
else
{
// Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
request.RequestFormat = DataFormat.Json;
}
request.AddJsonBody(options.Data);
}
}
if (options.FileParameters != null)
{
foreach (var fileParam in options.FileParameters)
{
var bytes = ClientUtils.ReadAsBytes(fileParam.Value);
var fileStream = fileParam.Value as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()
};
if (response.Headers != null)
{
foreach (var responseHeader in response.Headers)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
{
transformed.Cookies.Add(
new Cookie(
responseCookies.Name,
responseCookies.Value,
responseCookies.Path,
responseCookies.Domain)
);
}
}
return transformed;
}
private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration)
{
RestClient client = new RestClient(_baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = client.Execute<T>(req);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
RestClient client = new RestClient(_baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
#region IAsynchronousClient
/// <summary>
/// Make a HTTP GET request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP POST request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PUT request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP DELETE request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP HEAD request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP OPTION request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PATCH request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken);
}
#endregion IAsynchronousClient
#region ISynchronousClient
/// <summary>
/// Make a HTTP GET request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config);
}
/// <summary>
/// Make a HTTP POST request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config);
}
/// <summary>
/// Make a HTTP PUT request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config);
}
/// <summary>
/// Make a HTTP DELETE request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config);
}
/// <summary>
/// Make a HTTP HEAD request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config);
}
/// <summary>
/// Make a HTTP OPTION request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config);
}
/// <summary>
/// Make a HTTP PATCH request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config);
}
#endregion ISynchronousClient
}
}

View File

@ -0,0 +1,68 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// API Exception
/// </summary>
public class ApiException : Exception
{
/// <summary>
/// Gets or sets the error code (HTTP status code)
/// </summary>
/// <value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary>
/// Gets or sets the error content (body json object)
/// </summary>
/// <value>The error content (Http response body).</value>
public object ErrorContent { get; private set; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
public ApiException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
public ApiException(int errorCode, string message) : base(message)
{
this.ErrorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
/// <param name="errorContent">Error content.</param>
/// <param name="headers">HTTP Headers.</param>
public ApiException(int errorCode, string message, object errorContent = null, Multimap<string, string> headers = null) : base(message)
{
this.ErrorCode = errorCode;
this.ErrorContent = errorContent;
this.Headers = headers;
}
}
}

View File

@ -0,0 +1,166 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Provides a non-generic contract for the ApiResponse wrapper.
/// </summary>
public interface IApiResponse
{
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
Type ResponseType { get; }
/// <summary>
/// The content of this response
/// </summary>
Object Content { get; }
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
List<Cookie> Cookies { get; set; }
/// <summary>
/// The raw content of this response
/// </summary>
string RawContent { get; }
}
/// <summary>
/// API Response
/// </summary>
public class ApiResponse<T> : IApiResponse
{
#region Properties
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets the data (parsed HTTP body)
/// </summary>
/// <value>The data.</value>
public T Data { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
public string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
public List<Cookie> Cookies { get; set; }
/// <summary>
/// The content of this response
/// </summary>
public Type ResponseType
{
get { return typeof(T); }
}
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
public object Content
{
get { return Data; }
}
/// <summary>
/// The raw content
/// </summary>
public string RawContent { get; }
#endregion Properties
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data, string rawContent)
{
StatusCode = statusCode;
Headers = headers;
Data = data;
RawContent = rawContent;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data) : this(statusCode, headers, data, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null)
{
}
#endregion Constructors
}
}

View File

@ -0,0 +1,229 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Utility functions providing some benefit to API client consumers.
/// </summary>
public static class ClientUtils
{
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
return match.Success ? match.Groups[1].Value : filename;
}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="collectionFormat">The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi</param>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A multimap of keys with 1..n associated values.</returns>
public static Multimap<string, string> ParameterToMultiMap(string collectionFormat, string name, object value)
{
var parameters = new Multimap<string, string>();
if (value is ICollection collection && collectionFormat == "multi")
{
foreach (var item in collection)
{
parameters.Add(name, ParameterToString(item));
}
}
else if (value is IDictionary dictionary)
{
if(collectionFormat == "deepObject") {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value));
}
}
else {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value));
}
}
}
else
{
parameters.Add(name, ParameterToString(value));
}
return parameters;
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="configuration">An optional configuration instance, providing formatting options used in processing.</param>
/// <returns>Formatted string.</returns>
public static string ParameterToString(object obj, IReadableConfiguration configuration = null)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is DateTimeOffset dateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is bool boolean)
return boolean ? "true" : "false";
if (obj is ICollection collection)
return string.Join(",", collection.Cast<object>());
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">string to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">string to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="inputStream">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON type exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public static string SelectHeaderContentType(string[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType))
return contentType;
}
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public static string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return string.Join(",", accepts);
}
/// <summary>
/// Provides a case-insensitive check that a provided content type is a known JSON-like content type.
/// </summary>
public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
/// <summary>
/// Check if the given MIME is a JSON MIME.
/// JSON MIME examples:
/// application/json
/// application/json; charset=UTF8
/// APPLICATION/JSON
/// application/vnd.company+json
/// </summary>
/// <param name="mime">MIME</param>
/// <returns>Returns True if MIME type is json.</returns>
public static bool IsJsonMime(string mime)
{
if (string.IsNullOrWhiteSpace(mime)) return false;
return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}
}
}

View File

@ -0,0 +1,515 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration : IReadableConfiguration
{
#region Constants
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Identifier for ISO 8601 DateTime Format
/// </summary>
/// <remarks>See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information.</remarks>
// ReSharper disable once InconsistentNaming
public const string ISO8601_DATETIME_FORMAT = "o";
#endregion Constants
#region Static Members
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
var status = (int)response.StatusCode;
if (status >= 400)
{
return new ApiException(status,
string.Format("Error calling {0}: {1}", methodName, response.RawContent),
response.RawContent, response.Headers);
}
return null;
};
#endregion Static Members
#region Private Members
/// <summary>
/// Defines the base path of the target API server.
/// Example: http://localhost:3000/v1/
/// </summary>
private string _basePath;
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// This is the key and value comprising the "secret" for acessing an API.
/// </summary>
/// <value>The API key.</value>
private IDictionary<string, string> _apiKey;
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
private IDictionary<string, string> _apiKeyPrefix;
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the servers defined in the OpenAPI spec.
/// </summary>
/// <value>The servers</value>
private IList<IReadOnlyDictionary<string, object>> _servers;
#endregion Private Members
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
BasePath = "http://petstore.swagger.io/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
ApiKeyPrefix = new ConcurrentDictionary<string, string>();
Servers = new List<IReadOnlyDictionary<string, object>>()
{
{
new Dictionary<string, object> {
{"url", "http://petstore.swagger.io/v2"},
{"description", "No description provided"},
}
}
};
// Setting Timeout has side effects (forces ApiClient creation).
Timeout = 100000;
}
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration(
IDictionary<string, string> defaultHeaders,
IDictionary<string, string> apiKey,
IDictionary<string, string> apiKeyPrefix,
string basePath = "http://petstore.swagger.io/v2") : this()
{
if (string.IsNullOrWhiteSpace(basePath))
throw new ArgumentException("The provided basePath is invalid.", "basePath");
if (defaultHeaders == null)
throw new ArgumentNullException("defaultHeaders");
if (apiKey == null)
throw new ArgumentNullException("apiKey");
if (apiKeyPrefix == null)
throw new ArgumentNullException("apiKeyPrefix");
BasePath = basePath;
foreach (var keyValuePair in defaultHeaders)
{
DefaultHeaders.Add(keyValuePair);
}
foreach (var keyValuePair in apiKey)
{
ApiKey.Add(keyValuePair);
}
foreach (var keyValuePair in apiKeyPrefix)
{
ApiKeyPrefix.Add(keyValuePair);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the base path for API access.
/// </summary>
public virtual string BasePath {
get { return _basePath; }
set { _basePath = value; }
}
/// <summary>
/// Gets or sets the default header.
/// </summary>
[Obsolete("Use DefaultHeaders instead.")]
public virtual IDictionary<string, string> DefaultHeader
{
get
{
return DefaultHeaders;
}
set
{
DefaultHeaders = value;
}
}
/// <summary>
/// Gets or sets the default headers.
/// </summary>
public virtual IDictionary<string, string> DefaultHeaders { get; set; }
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
public virtual int Timeout { get; set; }
/// <summary>
/// Gets or sets the proxy
/// </summary>
/// <value>Proxy.</value>
public virtual WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public virtual string UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public virtual string Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public virtual string Password { get; set; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix(string apiKeyIdentifier)
{
string apiKeyValue;
ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue);
string apiKeyPrefix;
if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix))
{
return apiKeyPrefix + " " + apiKeyValue;
}
return apiKeyValue;
}
/// <summary>
/// Gets or sets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
public X509CertificateCollection ClientCertificates { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
///
/// This helper property simplifies code generation.
/// </summary>
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public virtual string TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (string.IsNullOrEmpty(value))
{
_tempFolderPath = Path.GetTempPath();
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
{
_tempFolderPath = value;
}
else
{
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
}
/// <summary>
/// Gets or sets the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public virtual string DateTimeFormat
{
get { return _dateTimeFormat; }
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
///
/// Whatever you set here will be prepended to the value defined in AddApiKey.
///
/// An example invocation here might be:
/// <example>
/// ApiKeyPrefix["Authorization"] = "Bearer";
/// </example>
/// … where ApiKey["Authorization"] would then be used to set the value of your bearer token.
///
/// <remarks>
/// OAuth2 workflows should set tokens via AccessToken.
/// </remarks>
/// </summary>
/// <value>The prefix of the API key.</value>
public virtual IDictionary<string, string> ApiKeyPrefix
{
get { return _apiKeyPrefix; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKeyPrefix collection may not be null.");
}
_apiKeyPrefix = value;
}
}
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public virtual IDictionary<string, string> ApiKey
{
get { return _apiKey; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKey collection may not be null.");
}
_apiKey = value;
}
}
/// <summary>
/// Gets or sets the servers.
/// </summary>
/// <value>The servers.</value>
public virtual IList<IReadOnlyDictionary<string, object>> Servers
{
get { return _servers; }
set
{
if (value == null)
{
throw new InvalidOperationException("Servers may not be null.");
}
_servers = value;
}
}
/// <summary>
/// Returns URL based on server settings without providing values
/// for the variables
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index)
{
return GetServerUrl(index, null);
}
/// <summary>
/// Returns URL based on server settings.
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index, Dictionary<string, string> inputVariables)
{
if (index < 0 || index >= Servers.Count)
{
throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}.");
}
if (inputVariables == null)
{
inputVariables = new Dictionary<string, string>();
}
IReadOnlyDictionary<string, object> server = Servers[index];
string url = (string)server["url"];
// go through variable and assign a value
foreach (KeyValuePair<string, object> variable in (IReadOnlyDictionary<string, object>)server["variables"])
{
IReadOnlyDictionary<string, object> serverVariables = (IReadOnlyDictionary<string, object>)(variable.Value);
if (inputVariables.ContainsKey(variable.Key))
{
if (((List<string>)serverVariables["enum_values"]).Contains(inputVariables[variable.Key]))
{
url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]);
}
else
{
throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List<string>)serverVariables["enum_values"]}");
}
}
else
{
// use defualt value
url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]);
}
}
return url;
}
#endregion Properties
#region Methods
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static string ToDebugReport()
{
string report = "C# SDK (Org.OpenAPITools) Debug Report:\n";
report += " OS: " + System.Environment.OSVersion + "\n";
report += " .NET Framework Version: " + System.Environment.Version + "\n";
report += " Version of the API: 1.0.0\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
/// <summary>
/// Add Api Key Header.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
/// <returns></returns>
public void AddApiKey(string key, string value)
{
ApiKey[key] = value;
}
/// <summary>
/// Sets the API key prefix.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
public void AddApiKeyPrefix(string key, string value)
{
ApiKeyPrefix[key] = value;
}
#endregion Methods
#region Static Members
/// <summary>
/// Merge configurations.
/// </summary>
/// <param name="first">First configuration.</param>
/// <param name="second">Second configuration.</param>
/// <return>Merged configuration.</return>
public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second)
{
if (second == null) return first ?? GlobalConfiguration.Instance;
Dictionary<string, string> apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value;
foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value;
foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value;
var config = new Configuration
{
ApiKey = apiKey,
ApiKeyPrefix = apiKeyPrefix,
DefaultHeaders = defaultHeaders,
BasePath = second.BasePath ?? first.BasePath,
Timeout = second.Timeout,
Proxy = second.Proxy ?? first.Proxy,
UserAgent = second.UserAgent ?? first.UserAgent,
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat
};
return config;
}
#endregion Static Members
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// A delegate to ExceptionFactory method
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="response">Response</param>
/// <returns>Exceptions</returns>
public delegate Exception ExceptionFactory(string methodName, IApiResponse response);
}

View File

@ -0,0 +1,67 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System.Collections.Generic;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// <see cref="GlobalConfiguration"/> provides a compile-time extension point for globally configuring
/// API Clients.
/// </summary>
/// <remarks>
/// A customized implementation via partial class may reside in another file and may
/// be excluded from automatic generation via a .openapi-generator-ignore file.
/// </remarks>
public partial class GlobalConfiguration : Configuration
{
#region Private Members
private static readonly object GlobalConfigSync = new { };
private static IReadableConfiguration _globalConfiguration;
#endregion Private Members
#region Constructors
/// <inheritdoc />
private GlobalConfiguration()
{
}
/// <inheritdoc />
public GlobalConfiguration(IDictionary<string, string> defaultHeader, IDictionary<string, string> apiKey, IDictionary<string, string> apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath)
{
}
static GlobalConfiguration()
{
Instance = new GlobalConfiguration();
}
#endregion Constructors
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static IReadableConfiguration Instance
{
get { return _globalConfiguration; }
set
{
lock (GlobalConfigSync)
{
_globalConfiguration = value;
}
}
}
}
}

View File

@ -0,0 +1,33 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Http methods supported by swagger
/// </summary>
public enum HttpMethod
{
/// <summary>HTTP GET request.</summary>
Get,
/// <summary>HTTP POST request.</summary>
Post,
/// <summary>HTTP PUT request.</summary>
Put,
/// <summary>HTTP DELETE request.</summary>
Delete,
/// <summary>HTTP HEAD request.</summary>
Head,
/// <summary>HTTP OPTIONS request.</summary>
Options,
/// <summary>HTTP PATCH request.</summary>
Patch
}
}

View File

@ -0,0 +1,37 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents configuration aspects required to interact with the API endpoints.
/// </summary>
public interface IApiAccessor
{
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
string GetBasePath();
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
ExceptionFactory ExceptionFactory { get; set; }
}
}

View File

@ -0,0 +1,100 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Contract for Asynchronous RESTful API interactions.
///
/// This interface allows consumers to provide a custom API accessor client.
/// </summary>
public interface IAsynchronousClient
{
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the GET http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the POST http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the PUT http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the DELETE http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the HEAD http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the OPTIONS http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the PATCH http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}

View File

@ -0,0 +1,115 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents a readable-only configuration contract.
/// </summary>
public interface IReadableConfiguration
{
/// <summary>
/// Gets the access token.
/// </summary>
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the API key.
/// </summary>
/// <value>API key.</value>
IDictionary<string, string> ApiKey { get; }
/// <summary>
/// Gets the API key prefix.
/// </summary>
/// <value>API key prefix.</value>
IDictionary<string, string> ApiKeyPrefix { get; }
/// <summary>
/// Gets the base path.
/// </summary>
/// <value>Base path.</value>
string BasePath { get; }
/// <summary>
/// Gets the date time format.
/// </summary>
/// <value>Date time foramt.</value>
string DateTimeFormat { get; }
/// <summary>
/// Gets the default header.
/// </summary>
/// <value>Default header.</value>
[Obsolete("Use DefaultHeaders instead.")]
IDictionary<string, string> DefaultHeader { get; }
/// <summary>
/// Gets the default headers.
/// </summary>
/// <value>Default headers.</value>
IDictionary<string, string> DefaultHeaders { get; }
/// <summary>
/// Gets the temp folder path.
/// </summary>
/// <value>Temp folder path.</value>
string TempFolderPath { get; }
/// <summary>
/// Gets the HTTP connection timeout (in milliseconds)
/// </summary>
/// <value>HTTP connection timeout.</value>
int Timeout { get; }
/// <summary>
/// Gets the proxy.
/// </summary>
/// <value>Proxy.</value>
WebProxy Proxy { get; }
/// <summary>
/// Gets the user agent.
/// </summary>
/// <value>User agent.</value>
string UserAgent { get; }
/// <summary>
/// Gets the username.
/// </summary>
/// <value>Username.</value>
string Username { get; }
/// <summary>
/// Gets the password.
/// </summary>
/// <value>Password.</value>
string Password { get; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
string GetApiKeyWithPrefix(string apiKeyIdentifier);
/// <summary>
/// Gets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
X509CertificateCollection ClientCertificates { get; }
}
}

View File

@ -0,0 +1,93 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Contract for Synchronous RESTful API interactions.
///
/// This interface allows consumers to provide a custom API accessor client.
/// </summary>
public interface ISynchronousClient
{
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the GET http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the POST http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the PUT http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the DELETE http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the HEAD http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the OPTIONS http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the PATCH http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
}
}

View File

@ -0,0 +1,295 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// A dictionary in which one key has many associated values.
/// </summary>
/// <typeparam name="TKey">The type of the key</typeparam>
/// <typeparam name="TValue">The type of the value associated with the key.</typeparam>
public class Multimap<TKey, TValue> : IDictionary<TKey, IList<TValue>>
{
#region Private Fields
private readonly Dictionary<TKey, IList<TValue>> _dictionary;
#endregion Private Fields
#region Constructors
/// <summary>
/// Empty Constructor.
/// </summary>
public Multimap()
{
_dictionary = new Dictionary<TKey, IList<TValue>>();
}
/// <summary>
/// Constructor with comparer.
/// </summary>
/// <param name="comparer"></param>
public Multimap(IEqualityComparer<TKey> comparer)
{
_dictionary = new Dictionary<TKey, IList<TValue>>(comparer);
}
#endregion Constructors
#region Enumerators
/// <summary>
/// To get the enumerator.
/// </summary>
/// <returns>Enumerator</returns>
public IEnumerator<KeyValuePair<TKey, IList<TValue>>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
/// <summary>
/// To get the enumerator.
/// </summary>
/// <returns>Enumerator</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion Enumerators
#region Public Members
/// <summary>
/// Add values to Multimap
/// </summary>
/// <param name="item">Key value pair</param>
public void Add(KeyValuePair<TKey, IList<TValue>> item)
{
if (!TryAdd(item.Key, item.Value))
throw new InvalidOperationException("Could not add values to Multimap.");
}
/// <summary>
/// Add Multimap to Multimap
/// </summary>
/// <param name="multimap">Multimap</param>
public void Add(Multimap<TKey, TValue> multimap)
{
foreach (var item in multimap)
{
if (!TryAdd(item.Key, item.Value))
throw new InvalidOperationException("Could not add values to Multimap.");
}
}
/// <summary>
/// Clear Multimap
/// </summary>
public void Clear()
{
_dictionary.Clear();
}
/// <summary>
/// Determines whether Multimap contains the specified item.
/// </summary>
/// <param name="item">Key value pair</param>
/// <exception cref="NotImplementedException">Method needs to be implemented</exception>
/// <returns>true if the Multimap contains the item; otherwise, false.</returns>
public bool Contains(KeyValuePair<TKey, IList<TValue>> item)
{
throw new NotImplementedException();
}
/// <summary>
/// Copy items of the Multimap to an array,
/// starting at a particular array index.
/// </summary>
/// <param name="array">The array that is the destination of the items copied
/// from Multimap. The array must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
/// <exception cref="NotImplementedException">Method needs to be implemented</exception>
public void CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
/// <summary>
/// Removes the specified item from the Multimap.
/// </summary>
/// <param name="item">Key value pair</param>
/// <returns>true if the item is successfully removed; otherwise, false.</returns>
/// <exception cref="NotImplementedException">Method needs to be implemented</exception>
public bool Remove(KeyValuePair<TKey, IList<TValue>> item)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the number of items contained in the Multimap.
/// </summary>
public int Count => _dictionary.Count;
/// <summary>
/// Gets a value indicating whether the Multimap is read-only.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Adds an item with the provided key and value to the Multimap.
/// </summary>
/// <param name="key">The object to use as the key of the item to add.</param>
/// <param name="value">The object to use as the value of the item to add.</param>
/// <exception cref="InvalidOperationException">Thrown when couldn't add the value to Multimap.</exception>
public void Add(TKey key, IList<TValue> value)
{
if (value != null && value.Count > 0)
{
if (_dictionary.TryGetValue(key, out var list))
{
foreach (var k in value) list.Add(k);
}
else
{
list = new List<TValue>(value);
if (!TryAdd(key, list))
throw new InvalidOperationException("Could not add values to Multimap.");
}
}
}
/// <summary>
/// Determines whether the Multimap contains an item with the specified key.
/// </summary>
/// <param name="key">The key to locate in the Multimap.</param>
/// <returns>true if the Multimap contains an item with
/// the key; otherwise, false.</returns>
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
/// <summary>
/// Removes item with the specified key from the Multimap.
/// </summary>
/// <param name="key">The key to locate in the Multimap.</param>
/// <returns>true if the item is successfully removed; otherwise, false.</returns>
public bool Remove(TKey key)
{
return TryRemove(key, out var _);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the
/// key is found; otherwise, the default value for the type of the value parameter.
/// This parameter is passed uninitialized.</param>
/// <returns> true if the object that implements Multimap contains
/// an item with the specified key; otherwise, false.</returns>
public bool TryGetValue(TKey key, out IList<TValue> value)
{
return _dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Gets or sets the item with the specified key.
/// </summary>
/// <param name="key">The key of the item to get or set.</param>
/// <returns>The value of the specified key.</returns>
public IList<TValue> this[TKey key]
{
get => _dictionary[key];
set => _dictionary[key] = value;
}
/// <summary>
/// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap.
/// </summary>
public ICollection<TKey> Keys => _dictionary.Keys;
/// <summary>
/// Gets a System.Collections.Generic.ICollection containing the values of the Multimap.
/// </summary>
public ICollection<IList<TValue>> Values => _dictionary.Values;
/// <summary>
/// Copy the items of the Multimap to an System.Array,
/// starting at a particular System.Array index.
/// </summary>
/// <param name="array">The one-dimensional System.Array that is the destination of the items copied
/// from Multimap. The System.Array must have zero-based indexing.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(Array array, int index)
{
((ICollection)_dictionary).CopyTo(array, index);
}
/// <summary>
/// Adds an item with the provided key and value to the Multimap.
/// </summary>
/// <param name="key">The object to use as the key of the item to add.</param>
/// <param name="value">The object to use as the value of the item to add.</param>
/// <exception cref="InvalidOperationException">Thrown when couldn't add value to Multimap.</exception>
public void Add(TKey key, TValue value)
{
if (value != null)
{
if (_dictionary.TryGetValue(key, out var list))
{
list.Add(value);
}
else
{
list = new List<TValue> { value };
if (!TryAdd(key, list))
throw new InvalidOperationException("Could not add value to Multimap.");
}
}
}
#endregion Public Members
#region Private Members
/**
* Helper method to encapsulate generator differences between dictionary types.
*/
private bool TryRemove(TKey key, out IList<TValue> value)
{
_dictionary.TryGetValue(key, out value);
return _dictionary.Remove(key);
}
/**
* Helper method to encapsulate generator differences between dictionary types.
*/
private bool TryAdd(TKey key, IList<TValue> value)
{
try
{
_dictionary.Add(key, value);
}
catch (ArgumentException)
{
return false;
}
return true;
}
#endregion Private Members
}
}

View File

@ -0,0 +1,29 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json.Converters;
namespace Org.OpenAPITools.Client
{
/// <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>
public class OpenAPIDateConverter : IsoDateTimeConverter
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenAPIDateConverter" /> class.
/// </summary>
public OpenAPIDateConverter()
{
// full-date = date-fullyear "-" date-month "-" date-mday
DateTimeFormat = "yyyy-MM-dd";
}
}
}

View File

@ -0,0 +1,74 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// A container for generalized request inputs. This type allows consumers to extend the request functionality
/// by abstracting away from the default (built-in) request framework (e.g. RestSharp).
/// </summary>
public class RequestOptions
{
/// <summary>
/// Parameters to be bound to path parts of the Request's URL
/// </summary>
public Dictionary<string, string> PathParameters { get; set; }
/// <summary>
/// Query parameters to be applied to the request.
/// Keys may have 1 or more values associated.
/// </summary>
public Multimap<string, string> QueryParameters { get; set; }
/// <summary>
/// Header parameters to be applied to to the request.
/// Keys may have 1 or more values associated.
/// </summary>
public Multimap<string, string> HeaderParameters { get; set; }
/// <summary>
/// Form parameters to be sent along with the request.
/// </summary>
public Dictionary<string, string> FormParameters { get; set; }
/// <summary>
/// File parameters to be sent along with the request.
/// </summary>
public Dictionary<string, Stream> FileParameters { get; set; }
/// <summary>
/// Cookies to be sent along with the request.
/// </summary>
public List<Cookie> Cookies { get; set; }
/// <summary>
/// Any data associated with a request body.
/// </summary>
public Object Data { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>
public RequestOptions()
{
PathParameters = new Dictionary<string, string>();
QueryParameters = new Multimap<string, string>();
HeaderParameters = new Multimap<string, string>();
FormParameters = new Dictionary<string, string>();
FileParameters = new Dictionary<string, Stream>();
Cookies = new List<Cookie>();
}
}
}

View File

@ -0,0 +1,21 @@
using Polly;
using RestSharp;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Configuration class to set the polly retry policies to be applied to the requests.
/// </summary>
public class RetryConfiguration
{
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -0,0 +1,76 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification
/// </summary>
public abstract partial class AbstractOpenAPISchema
{
/// <summary>
/// Custom JSON serializer
/// </summary>
static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
MissingMemberHandling = MissingMemberHandling.Error,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Custom JSON serializer for objects with additional properties
/// </summary>
static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Gets or Sets the actual instance
/// </summary>
public abstract Object ActualInstance { get; set; }
/// <summary>
/// Gets or Sets IsNullable to indicate whether the instance is nullable
/// </summary>
public bool IsNullable { get; protected set; }
/// <summary>
/// Gets or Sets the schema type, which can be either `oneOf` or `anyOf`
/// </summary>
public string SchemaType { get; protected set; }
/// <summary>
/// Converts the instance into JSON string.
/// </summary>
public abstract string ToJson();
}
}

View File

@ -66,6 +66,7 @@ docs/ParentPet.md
docs/Pet.md
docs/PetApi.md
docs/Pig.md
docs/Pineapple.md
docs/Quadrilateral.md
docs/QuadrilateralInterface.md
docs/ReadOnlyFirst.md
@ -178,6 +179,7 @@ src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java
src/main/java/org/openapitools/client/model/ParentPet.java
src/main/java/org/openapitools/client/model/Pet.java
src/main/java/org/openapitools/client/model/Pig.java
src/main/java/org/openapitools/client/model/Pineapple.java
src/main/java/org/openapitools/client/model/Quadrilateral.java
src/main/java/org/openapitools/client/model/QuadrilateralInterface.java
src/main/java/org/openapitools/client/model/ReadOnlyFirst.java

View File

@ -213,6 +213,7 @@ Class | Method | HTTP request | Description
- [ParentPet](docs/ParentPet.md)
- [Pet](docs/Pet.md)
- [Pig](docs/Pig.md)
- [Pineapple](docs/Pineapple.md)
- [Quadrilateral](docs/Quadrilateral.md)
- [QuadrilateralInterface](docs/QuadrilateralInterface.md)
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)

View File

@ -2053,6 +2053,11 @@ components:
pattern: /^[A-Z\s]*$/i
type: string
type: object
pineapple:
properties:
origin:
type: string
type: object
banana:
properties:
lengthCm:
@ -2113,6 +2118,7 @@ components:
gmFruit:
additionalProperties: false
anyOf:
- $ref: '#/components/schemas/pineapple'
- $ref: '#/components/schemas/apple'
- $ref: '#/components/schemas/banana'
properties:

View File

@ -8,8 +8,8 @@
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**color** | **String** | | [optional]
**cultivar** | **String** | | [optional]
**origin** | **String** | | [optional]
**cultivar** | **String** | | [optional]
**lengthCm** | **BigDecimal** | | [optional]

View File

@ -0,0 +1,13 @@
# Pineapple
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**origin** | **String** | | [optional]

View File

@ -270,6 +270,7 @@ public class JSON {
.registerTypeAdapterFactory(new org.openapitools.client.model.ParentPet.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Pig.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Pineapple.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Quadrilateral.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.QuadrilateralInterface.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory())

View File

@ -78,16 +78,23 @@ public class Fruit extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Fruit>() {
@Override
public void write(JsonWriter out, Fruit value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Apple`
if (value.getActualInstance() instanceof Apple) {
JsonObject obj = adapterApple.toJsonTree((Apple)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Banana`
if (value.getActualInstance() instanceof Banana) {
JsonObject obj = adapterBanana.toJsonTree((Banana)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Apple, Banana");

View File

@ -78,16 +78,23 @@ public class FruitReq extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<FruitReq>() {
@Override
public void write(JsonWriter out, FruitReq value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `AppleReq`
if (value.getActualInstance() instanceof AppleReq) {
JsonObject obj = adapterAppleReq.toJsonTree((AppleReq)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `BananaReq`
if (value.getActualInstance() instanceof BananaReq) {
JsonObject obj = adapterBananaReq.toJsonTree((BananaReq)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: AppleReq, BananaReq");

View File

@ -26,6 +26,7 @@ import java.io.IOException;
import java.math.BigDecimal;
import org.openapitools.client.model.Apple;
import org.openapitools.client.model.Banana;
import org.openapitools.client.model.Pineapple;
import javax.ws.rs.core.GenericType;
@ -74,23 +75,38 @@ public class GmFruit extends AbstractOpenApiSchema {
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Apple> adapterApple = gson.getDelegateAdapter(this, TypeToken.get(Apple.class));
final TypeAdapter<Banana> adapterBanana = gson.getDelegateAdapter(this, TypeToken.get(Banana.class));
final TypeAdapter<Pineapple> adapterPineapple = gson.getDelegateAdapter(this, TypeToken.get(Pineapple.class));
return (TypeAdapter<T>) new TypeAdapter<GmFruit>() {
@Override
public void write(JsonWriter out, GmFruit value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Apple`
if (value.getActualInstance() instanceof Apple) {
JsonObject obj = adapterApple.toJsonTree((Apple)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Banana`
if (value.getActualInstance() instanceof Banana) {
JsonObject obj = adapterBanana.toJsonTree((Banana)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match anyOf schemas: Apple, Banana");
// check if the actual instance is of the type `Pineapple`
if (value.getActualInstance() instanceof Pineapple) {
JsonObject obj = adapterPineapple.toJsonTree((Pineapple)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match anyOf schemas: Apple, Banana, Pineapple");
}
@Override
@ -121,6 +137,18 @@ public class GmFruit extends AbstractOpenApiSchema {
log.log(Level.FINER, "Input data does not match schema 'Banana'", e);
}
// deserialize Pineapple
try {
deserialized = gson.fromJson(in, Pineapple.class);
log.log(Level.FINER, "Input data matches schema 'Pineapple'");
GmFruit ret = new GmFruit();
ret.setActualInstance(deserialized);
return ret;
} catch (Exception e) {
// deserialization failed, continue
log.log(Level.FINER, "Input data does not match schema 'Pineapple'", e);
}
throw new IOException("Failed deserialization for GmFruit: no match found.");
}
}.nullSafe();
@ -144,11 +172,18 @@ public class GmFruit extends AbstractOpenApiSchema {
setActualInstance(o);
}
public GmFruit(Pineapple o) {
super("anyOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("Apple", new GenericType<Apple>() {
});
schemas.put("Banana", new GenericType<Banana>() {
});
schemas.put("Pineapple", new GenericType<Pineapple>() {
});
}
@Override
@ -159,7 +194,7 @@ public class GmFruit extends AbstractOpenApiSchema {
/**
* Set the instance that matches the anyOf child schema, check
* the instance parameter is valid against the anyOf child schemas:
* Apple, Banana
* Apple, Banana, Pineapple
*
* It could be an instance of the 'anyOf' schemas.
* The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf).
@ -176,14 +211,19 @@ public class GmFruit extends AbstractOpenApiSchema {
return;
}
throw new RuntimeException("Invalid instance type. Must be Apple, Banana");
if (instance instanceof Pineapple) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be Apple, Banana, Pineapple");
}
/**
* Get the actual instance, which can be the following:
* Apple, Banana
* Apple, Banana, Pineapple
*
* @return The actual instance (Apple, Banana)
* @return The actual instance (Apple, Banana, Pineapple)
*/
@Override
public Object getActualInstance() {
@ -212,5 +252,16 @@ public class GmFruit extends AbstractOpenApiSchema {
return (Banana)super.getActualInstance();
}
/**
* Get the actual instance of `Pineapple`. If the actual instance is not `Pineapple`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Pineapple`
* @throws ClassCastException if the instance is not `Pineapple`
*/
public Pineapple getPineapple() throws ClassCastException {
return (Pineapple)super.getActualInstance();
}
}

View File

@ -79,22 +79,30 @@ public class Mammal extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Mammal>() {
@Override
public void write(JsonWriter out, Mammal value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Pig`
if (value.getActualInstance() instanceof Pig) {
JsonObject obj = adapterPig.toJsonTree((Pig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Whale`
if (value.getActualInstance() instanceof Whale) {
JsonObject obj = adapterWhale.toJsonTree((Whale)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Zebra`
if (value.getActualInstance() instanceof Zebra) {
JsonObject obj = adapterZebra.toJsonTree((Zebra)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Pig, Whale, Zebra");

View File

@ -77,16 +77,23 @@ public class NullableShape extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<NullableShape>() {
@Override
public void write(JsonWriter out, NullableShape value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");

View File

@ -77,16 +77,23 @@ public class Pig extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Pig>() {
@Override
public void write(JsonWriter out, Pig value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `BasquePig`
if (value.getActualInstance() instanceof BasquePig) {
JsonObject obj = adapterBasquePig.toJsonTree((BasquePig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `DanishPig`
if (value.getActualInstance() instanceof DanishPig) {
JsonObject obj = adapterDanishPig.toJsonTree((DanishPig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: BasquePig, DanishPig");

View File

@ -0,0 +1,162 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Pineapple
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Pineapple {
public static final String SERIALIZED_NAME_ORIGIN = "origin";
@SerializedName(SERIALIZED_NAME_ORIGIN)
private String origin;
public Pineapple() {
}
public Pineapple origin(String origin) {
this.origin = origin;
return this;
}
/**
* Get origin
* @return origin
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pineapple pineapple = (Pineapple) o;
return Objects.equals(this.origin, pineapple.origin);
}
@Override
public int hashCode() {
return Objects.hash(origin);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pineapple {\n");
sb.append(" origin: ").append(toIndentedString(origin)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("origin");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Pineapple.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Pineapple' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Pineapple> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Pineapple.class));
return (TypeAdapter<T>) new TypeAdapter<Pineapple>() {
@Override
public void write(JsonWriter out, Pineapple value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Pineapple read(JsonReader in) throws IOException {
JsonObject obj = elementAdapter.read(in).getAsJsonObject();
Set<Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry: entries) {
if (!Pineapple.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Pineapple` properties");
}
}
return thisAdapter.fromJsonTree(obj);
}
}.nullSafe();
}
}
}

View File

@ -77,16 +77,23 @@ public class Quadrilateral extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Quadrilateral>() {
@Override
public void write(JsonWriter out, Quadrilateral value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `ComplexQuadrilateral`
if (value.getActualInstance() instanceof ComplexQuadrilateral) {
JsonObject obj = adapterComplexQuadrilateral.toJsonTree((ComplexQuadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `SimpleQuadrilateral`
if (value.getActualInstance() instanceof SimpleQuadrilateral) {
JsonObject obj = adapterSimpleQuadrilateral.toJsonTree((SimpleQuadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral");

View File

@ -77,16 +77,23 @@ public class Shape extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Shape>() {
@Override
public void write(JsonWriter out, Shape value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");

View File

@ -77,16 +77,23 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<ShapeOrNull>() {
@Override
public void write(JsonWriter out, ShapeOrNull value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");

View File

@ -79,22 +79,30 @@ public class Triangle extends AbstractOpenApiSchema {
return (TypeAdapter<T>) new TypeAdapter<Triangle>() {
@Override
public void write(JsonWriter out, Triangle value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `EquilateralTriangle`
if (value.getActualInstance() instanceof EquilateralTriangle) {
JsonObject obj = adapterEquilateralTriangle.toJsonTree((EquilateralTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `IsoscelesTriangle`
if (value.getActualInstance() instanceof IsoscelesTriangle) {
JsonObject obj = adapterIsoscelesTriangle.toJsonTree((IsoscelesTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `ScaleneTriangle`
if (value.getActualInstance() instanceof ScaleneTriangle) {
JsonObject obj = adapterScaleneTriangle.toJsonTree((ScaleneTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle");

View File

@ -286,6 +286,36 @@ public class JSONTest {
return offset;
}
/**
* Validate an anyOf schema can be deserialized into the expected class.
* The anyOf schema does not have a discriminator.
*/
@Test
public void testAnyOfSchemaWithoutDiscriminator() throws Exception {
{
String str = "{ \"cultivar\": \"golden delicious\", \"origin\": \"japan\" }";
String str2 = "{ \"origin_typo\": \"japan\" }";
// make sure deserialization works for pojo object
Apple a = json.getGson().fromJson(str, Apple.class);
assertEquals(a.getCultivar(), "golden delicious");
assertEquals(a.getOrigin(), "japan");
GmFruit o = json.getGson().fromJson(str, GmFruit.class);
assertTrue(o.getActualInstance() instanceof Apple);
Apple inst = (Apple) o.getActualInstance();
assertEquals(inst.getCultivar(), "golden delicious");
assertEquals(inst.getOrigin(), "japan");
assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
// no match
Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
GmFruit o2 = json.getGson().fromJson(str2, GmFruit.class);
});
}
}
/**
* Validate a oneOf schema can be deserialized into the expected class.
* The oneOf schema does not have a discriminator.
@ -308,12 +338,20 @@ public class JSONTest {
assertEquals(inst.getCultivar(), "golden delicious");
assertEquals(inst.getMealy(), false);
assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
AppleReq inst2 = o.getAppleReq();
assertEquals(inst2.getCultivar(), "golden delicious");
assertEquals(inst2.getMealy(), false);
assertEquals(json.getGson().toJson(inst2), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
}
{
// test to ensure the oneOf object can be serialized to "null" correctly
FruitReq o = new FruitReq();
assertEquals(o.getActualInstance(), null);
assertEquals(json.getGson().toJson(o), "null");
assertEquals(json.getGson().toJson(null), "null");
}
{
// Same test, but this time with additional (undeclared) properties.
// Since FruitReq has additionalProperties: false, deserialization should fail.

View File

@ -0,0 +1,51 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for Pineapple
*/
public class PineappleTest {
private final Pineapple model = new Pineapple();
/**
* Model tests for Pineapple
*/
@Test
public void testPineapple() {
// TODO: test Pineapple
}
/**
* Test the property 'origin'
*/
@Test
public void originTest() {
// TODO: test origin
}
}