diff --git a/.github/workflows/samples-dotnet.yaml b/.github/workflows/samples-dotnet.yaml index 328a3527c8b4..c345dad28290 100644 --- a/.github/workflows/samples-dotnet.yaml +++ b/.github/workflows/samples-dotnet.yaml @@ -4,11 +4,13 @@ on: push: paths: - 'samples/client/petstore/csharp-netcore/**net6.0**/' + - 'samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore**/' - 'samples/server/petstore/aspnetcore-6.0/**' - 'samples/server/petstore/aspnetcore-6.0-pocoModels/**' pull_request: paths: - 'samples/client/petstore/csharp-netcore/**net6.0**/' + - 'samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore**/' - 'samples/server/petstore/aspnetcore-6.0/**' - 'samples/server/petstore/aspnetcore-6.0-pocoModels/**' jobs: @@ -22,6 +24,9 @@ jobs: # clients - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0 - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt + - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf + - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf + - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf - samples/server/petstore/aspnetcore-6.0 - samples/server/petstore/aspnetcore-6.0-pocoModels - samples/server/petstore/aspnetcore-6.0-project4Models diff --git a/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-allOf.yaml b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-allOf.yaml new file mode 100644 index 000000000000..7c2d2e4c4c29 --- /dev/null +++ b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-allOf.yaml @@ -0,0 +1,12 @@ +# for csharp-netcore generichost +generatorName: csharp-netcore +outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf +inputSpec: modules/openapi-generator/src/test/resources/3_0/allOf.yaml +library: generichost +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + targetFramework: net7.0 + nullableReferenceTypes: true diff --git a/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-anyOf.yaml b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-anyOf.yaml new file mode 100644 index 000000000000..98ec98991588 --- /dev/null +++ b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-anyOf.yaml @@ -0,0 +1,12 @@ +# for csharp-netcore generichost +generatorName: csharp-netcore +outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf +inputSpec: modules/openapi-generator/src/test/resources/3_0/anyOf.yaml +library: generichost +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + targetFramework: net7.0 + nullableReferenceTypes: true diff --git a/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-oneOf.yaml b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-oneOf.yaml new file mode 100644 index 000000000000..a670bb581218 --- /dev/null +++ b/bin/configs/csharp-netcore-OpenAPIClient-generichost-netcore-latest-oneOf.yaml @@ -0,0 +1,12 @@ +# for csharp-netcore generichost +generatorName: csharp-netcore +outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf.yaml +library: generichost +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + targetFramework: net7.0 + nullableReferenceTypes: true diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.gitignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES new file mode 100644 index 000000000000..f71328b618e2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES @@ -0,0 +1,41 @@ +.gitignore +Org.OpenAPITools.sln +README.md +appveyor.yml +docs/apis/DefaultApi.md +docs/models/Adult.md +docs/models/AdultAllOf.md +docs/models/Child.md +docs/models/ChildAllOf.md +docs/models/Person.md +docs/scripts/git_push.ps1 +docs/scripts/git_push.sh +src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/IApi.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs +src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +src/Org.OpenAPITools/Client/ApiResponse`1.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +src/Org.OpenAPITools/Client/HostConfiguration.cs +src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs +src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +src/Org.OpenAPITools/Client/TokenBase.cs +src/Org.OpenAPITools/Client/TokenContainer`1.cs +src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs +src/Org.OpenAPITools/Model/Adult.cs +src/Org.OpenAPITools/Model/AdultAllOf.cs +src/Org.OpenAPITools/Model/Child.cs +src/Org.OpenAPITools/Model/ChildAllOf.cs +src/Org.OpenAPITools/Model/Person.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION new file mode 100644 index 000000000000..d6b4ec4aa783 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/Org.OpenAPITools.sln b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/Org.OpenAPITools.sln new file mode 100644 index 000000000000..5b15451c9dcf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/README.md new file mode 100644 index 000000000000..f9c1c7f74621 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/README.md @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/appveyor.yml b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/apis/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/apis/DefaultApi.md new file mode 100644 index 000000000000..165d829775f8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/apis/DefaultApi.md @@ -0,0 +1,95 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://api.example.xyz/v1* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**List**](DefaultApi.md#list) | **GET** /person/display/{personId} | | + + +# **List** +> Person List (string personId) + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class ListExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://api.example.xyz/v1"; + var apiInstance = new DefaultApi(config); + var personId = "personId_example"; // string | The id of the person to retrieve + + try + { + Person result = apiInstance.List(personId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.List: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the ListWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.ListWithHttpInfo(personId); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.ListWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **personId** | **string** | The id of the person to retrieve | | + +### Return type + +[**Person**](Person.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Adult.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Adult.md new file mode 100644 index 000000000000..5f24d78cdaf3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Adult.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Adult +A representation of an adult + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Type** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/AdultAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/AdultAllOf.md new file mode 100644 index 000000000000..401f0b774387 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/AdultAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.AdultAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Children** | [**List<Child>**](Child.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Child.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Child.md new file mode 100644 index 000000000000..4c453728b243 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Child.md @@ -0,0 +1,14 @@ +# Org.OpenAPITools.Model.Child +A representation of a child + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Type** | **string** | | [optional] +**BoosterSeat** | **bool** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/ChildAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/ChildAllOf.md new file mode 100644 index 000000000000..14d559e334bc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/ChildAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ChildAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Age** | **int** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Person.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Person.md new file mode 100644 index 000000000000..42c19689f9a1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/models/Person.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Person + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Type** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.ps1 new file mode 100644 index 000000000000..73ed35c2bb10 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.ps1 @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "github.com", + [Parameter()][Alias("u")][String]$GitUserId = "GIT_USER_ID", + [Parameter()][Alias("r")][String]$GitRepoId = "GIT_REPO_ID", + [Parameter()][Alias("m")][string]$Message = "Minor update", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.sh b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.sh new file mode 100644 index 000000000000..882104922184 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/docs/scripts/git_push.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-GIT_USER_ID} +git_repo_id=${2:-GIT_REPO_ID} +release_note=${3:-Minor update} +git_host=${4:-github.com} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs new file mode 100644 index 000000000000..7cc496a25fc9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -0,0 +1,58 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + + }); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..a0d68acdbb0a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,65 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + public sealed class DefaultApiTests : ApiTestsBase + { + private readonly IApi.IDefaultApi _instance; + + public DefaultApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + + /// + /// Test List + /// + [Fact (Skip = "not implemented")] + public async Task ListAsyncTest() + { + string personId = default; + var response = await _instance.ListAsync(personId); + Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 000000000000..7200578a9cae --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -0,0 +1,103 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultAllOfTests.cs new file mode 100644 index 000000000000..d534024a85d2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultAllOfTests.cs @@ -0,0 +1,69 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AdultAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AdultAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AdultAllOf + //private AdultAllOf instance; + + public AdultAllOfTests() + { + // TODO uncomment below to create an instance of AdultAllOf + //instance = new AdultAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AdultAllOf + /// + [Fact] + public void AdultAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" AdultAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Children' + /// + [Fact] + public void ChildrenTest() + { + // TODO unit test for the property 'Children' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultTests.cs new file mode 100644 index 000000000000..026277c98bbf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/AdultTests.cs @@ -0,0 +1,61 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Adult + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AdultTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Adult + //private Adult instance; + + public AdultTests() + { + // TODO uncomment below to create an instance of Adult + //instance = new Adult(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Adult + /// + [Fact] + public void AdultInstanceTest() + { + // TODO uncomment below to test "IsType" Adult + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildAllOfTests.cs new file mode 100644 index 000000000000..54deefe89545 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildAllOfTests.cs @@ -0,0 +1,69 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ChildAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildAllOf + //private ChildAllOf instance; + + public ChildAllOfTests() + { + // TODO uncomment below to create an instance of ChildAllOf + //instance = new ChildAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildAllOf + /// + [Fact] + public void ChildAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" ChildAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Age' + /// + [Fact] + public void AgeTest() + { + // TODO unit test for the property 'Age' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildTests.cs new file mode 100644 index 000000000000..cb5362022489 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/ChildTests.cs @@ -0,0 +1,69 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Child + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Child + //private Child instance; + + public ChildTests() + { + // TODO uncomment below to create an instance of Child + //instance = new Child(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Child + /// + [Fact] + public void ChildInstanceTest() + { + // TODO uncomment below to test "IsType" Child + //Assert.IsType(instance); + } + + + /// + /// Test the property 'BoosterSeat' + /// + [Fact] + public void BoosterSeatTest() + { + // TODO unit test for the property 'BoosterSeat' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/PersonTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/PersonTests.cs new file mode 100644 index 000000000000..cd3e2caf4293 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Model/PersonTests.cs @@ -0,0 +1,103 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Person + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PersonTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Person + //private Person instance; + + public PersonTests() + { + // TODO uncomment below to create an instance of Person + //instance = new Person(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Person + /// + [Fact] + public void PersonInstanceTest() + { + // TODO uncomment below to test "IsType" Person + //Assert.IsType(instance); + } + + /// + /// Test deserialize a Adult from type Person + /// + [Fact] + public void AdultDeserializeFromPersonTest() + { + // TODO uncomment below to test deserialize a Adult from type Person + //Assert.IsType(JsonConvert.DeserializeObject(new Adult().ToJson())); + } + /// + /// Test deserialize a Child from type Person + /// + [Fact] + public void ChildDeserializeFromPersonTest() + { + // TODO uncomment below to test deserialize a Child from type Person + //Assert.IsType(JsonConvert.DeserializeObject(new Child().ToJson())); + } + + /// + /// Test the property 'FirstName' + /// + [Fact] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + /// + /// Test the property 'LastName' + /// + [Fact] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..96b9fd0c60e9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net7.0 + false + enable + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..c4de14ce7d9e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,252 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Person?>> + Task> ListWithHttpInfoAsync(string personId, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Person> + Task ListAsync(string personId, System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Person?> + Task ListOrDefaultAsync(string personId, System.Threading.CancellationToken? cancellationToken = null); + } +} + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IApi.IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + Logger = logger; + HttpClient = httpClient; + } + + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <> + public async Task ListAsync(string personId, System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse result = await ListWithHttpInfoAsync(personId, cancellationToken).ConfigureAwait(false); + + if (result.Content == null) + throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); + + return result.Content; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <> + public async Task ListOrDefaultAsync(string personId, System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse? result = null; + try + { + result = await ListWithHttpInfoAsync(personId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + } + + return result != null && result.IsSuccessStatusCode + ? result.Content + : null; + } + + /// + /// Validates the request parameters + /// + /// + /// + protected virtual string OnList(string personId) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (personId == null) + throw new ArgumentNullException(nameof(personId)); + + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + return personId; + } + + /// + /// Processes the server response + /// + /// + /// + protected virtual void AfterList(ApiResponse apiResponse, string personId) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + protected virtual void OnErrorList(Exception exception, string pathFormat, string path, string personId) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> ListWithHttpInfoAsync(string personId, System.Threading.CancellationToken? cancellationToken = null) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + personId = OnList(personId); + + using (HttpRequestMessage request = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress!.Port; + uriBuilder.Scheme = ClientUtils.SCHEME; + uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/person/display/{personId}"; + + uriBuilder.Path = uriBuilder.Path.Replace("%7BpersonId%7D", Uri.EscapeDataString(personId.ToString())); + + request.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + request.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) + { + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/person/display/{personId}", uriBuilder.Path)); + + string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); + + ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); + + if (apiResponse.IsSuccessStatusCode) + { + apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterList(apiResponse, personId); + } + + return apiResponse; + } + } + } + catch(Exception e) + { + OnErrorList(e, "/person/display/{personId}", uriBuilder.Path, personId); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 000000000000..038f19bcfa1a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..eaf62115550f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,52 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 000000000000..7757b89c191c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000000..f87e53e8b048 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -0,0 +1,58 @@ +using System; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health. + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The time the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The time the response was received. + /// + public DateTime ReceivedAt { get; } + + /// + /// The HttpStatusCode received. + /// + public HttpStatusCode HttpStatus { get; } + + /// + /// The path requested. + /// + public string PathFormat { get; } + + /// + /// The elapsed time from request to response. + /// + public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + + /// + /// The path + /// + public string Path { get; } + + /// + /// The event args used to track server health. + /// + /// + /// + /// + /// + /// + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) + { + RequestedAt = requestedAt; + ReceivedAt = receivedAt; + HttpStatus = httpStatus; + PathFormat = pathFormat; + Path = path; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs new file mode 100644 index 000000000000..878fae8c821c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -0,0 +1,109 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// The deserialized content + /// + public T? Content { get; internal set; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The raw data + /// + public string RawContent { get; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + public ApiResponse(System.Net.Http.HttpResponseMessage response, string rawContent) + { + StatusCode = response.StatusCode; + Headers = response.Headers; + IsSuccessStatusCode = response.IsSuccessStatusCode; + ReasonPhrase = response.ReasonPhrase; + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..b8b2d1069625 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,279 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is System.Collections.ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "http://api.example.xyz/v1"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "http"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = "/v1"; + + /// + /// The host of the API + /// + public const string HOST = "api.example.xyz"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 000000000000..85093b0c1fee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 000000000000..96237155e836 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000000..22311607841b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,76 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs new file mode 100644 index 000000000000..a4a094e420ab --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -0,0 +1,133 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides hosting configuration for Org.OpenAPITools + /// + public class HostConfiguration + where TDefaultApi : class, IApi.IDefaultApi + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new AdultJsonConverter()); + _jsonOptions.Converters.Add(new AdultAllOfJsonConverter()); + _jsonOptions.Converters.Add(new ChildJsonConverter()); + _jsonOptions.Converters.Add(new ChildAllOfJsonConverter()); + _jsonOptions.Converters.Add(new PersonJsonConverter()); + _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); + _services.AddSingleton(); + _services.AddTransient(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients + ( + Action? client = null, Action? builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000000..0184d9ad9446 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs new file mode 100644 index 000000000000..efab614258eb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -0,0 +1,49 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Threading.Channels; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Channel AvailableTokens { get; } + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens = Channel.CreateBounded(options); + + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null) + => await AvailableTokens.Reader.ReadAsync(cancellation.GetValueOrDefault()).ConfigureAwait(false); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenBase.cs new file mode 100644 index 000000000000..0faa2977dcf0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenBase.cs @@ -0,0 +1,71 @@ +// + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs new file mode 100644 index 000000000000..3fba287ad9d3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs @@ -0,0 +1,37 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs new file mode 100644 index 000000000000..29be81ec84f0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -0,0 +1,44 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Collections.Generic; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 000000000000..eb8ef354e74e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,77 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + => ConfigureApi(builder); + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 000000000000..9ff476c2ca95 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,79 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circiut breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 000000000000..b765454c522e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,101 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TDefaultApi : class, IApi.IDefaultApi + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs new file mode 100644 index 000000000000..848421f702e7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs @@ -0,0 +1,145 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// A representation of an adult + /// + public partial class Adult : Person, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// firstName + /// lastName + /// type + [JsonConstructor] + internal Adult(AdultAllOf adultAllOf, string firstName, string lastName, string type) : base(firstName, lastName, type) + { + AdultAllOf = adultAllOf; + } + + /// + /// Gets or Sets AdultAllOf + /// + public AdultAllOf AdultAllOf { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Adult {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type Adult + /// + public class AdultJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Adult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Utf8JsonReader adultAllOfReader = reader; + bool adultAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out AdultAllOf? adultAllOf); + + string firstName = default; + string lastName = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "firstName": + firstName = reader.GetString(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "$_type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new Adult(adultAllOf, firstName, lastName, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Adult adult, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("firstName", adult.FirstName); + writer.WriteString("lastName", adult.LastName); + writer.WriteString("$_type", adult.Type); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/AdultAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/AdultAllOf.cs new file mode 100644 index 000000000000..66b6d72e06f5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/AdultAllOf.cs @@ -0,0 +1,156 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// AdultAllOf + /// + public partial class AdultAllOf : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// children + [JsonConstructor] + public AdultAllOf(List children) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (children == null) + throw new ArgumentNullException("children is a required property for AdultAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Children = children; + } + + /// + /// Gets or Sets Children + /// + [JsonPropertyName("children")] + public List Children { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdultAllOf {\n"); + sb.Append(" Children: ").Append(Children).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type AdultAllOf + /// + public class AdultAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override AdultAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + List children = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "children": + children = JsonSerializer.Deserialize>(ref reader, options); + break; + default: + break; + } + } + } + + return new AdultAllOf(children); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdultAllOf adultAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WritePropertyName("children"); + JsonSerializer.Serialize(writer, adultAllOf.Children, options); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs new file mode 100644 index 000000000000..eff788fcdfb2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs @@ -0,0 +1,168 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// A representation of a child + /// + public partial class Child : Person, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// boosterSeat + /// firstName + /// lastName + /// type + [JsonConstructor] + public Child(ChildAllOf childAllOf, bool boosterSeat, string firstName, string lastName, string type) : base(firstName, lastName, type) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (boosterSeat == null) + throw new ArgumentNullException("boosterSeat is a required property for Child and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + ChildAllOf = childAllOf; + BoosterSeat = boosterSeat; + } + + /// + /// Gets or Sets ChildAllOf + /// + public ChildAllOf ChildAllOf { get; set; } + + /// + /// Gets or Sets BoosterSeat + /// + [JsonPropertyName("boosterSeat")] + public bool BoosterSeat { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Child {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" BoosterSeat: ").Append(BoosterSeat).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type Child + /// + public class ChildJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Child Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Utf8JsonReader childAllOfReader = reader; + bool childAllOfDeserialized = Client.ClientUtils.TryDeserialize(ref reader, options, out ChildAllOf? childAllOf); + + bool boosterSeat = default; + string firstName = default; + string lastName = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "boosterSeat": + boosterSeat = reader.GetBoolean(); + break; + case "firstName": + firstName = reader.GetString(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "$_type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new Child(childAllOf, boosterSeat, firstName, lastName, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Child child, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean("boosterSeat", child.BoosterSeat); + writer.WriteString("firstName", child.FirstName); + writer.WriteString("lastName", child.LastName); + writer.WriteString("$_type", child.Type); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/ChildAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/ChildAllOf.cs new file mode 100644 index 000000000000..991b76b387bc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/ChildAllOf.cs @@ -0,0 +1,155 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ChildAllOf + /// + public partial class ChildAllOf : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// age + [JsonConstructor] + public ChildAllOf(int age) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (age == null) + throw new ArgumentNullException("age is a required property for ChildAllOf and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Age = age; + } + + /// + /// Gets or Sets Age + /// + [JsonPropertyName("age")] + public int Age { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ChildAllOf {\n"); + sb.Append(" Age: ").Append(Age).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type ChildAllOf + /// + public class ChildAllOfJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override ChildAllOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + int age = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "age": + age = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new ChildAllOf(age); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChildAllOf childAllOf, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("age", childAllOf.Age); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs new file mode 100644 index 000000000000..5e85da6a1520 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs @@ -0,0 +1,199 @@ +// +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Person + /// + public partial class Person : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// firstName + /// lastName + /// type + [JsonConstructor] + public Person(string firstName, string lastName, string type) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (type == null) + throw new ArgumentNullException("type is a required property for Person and cannot be null."); + + if (lastName == null) + throw new ArgumentNullException("lastName is a required property for Person and cannot be null."); + + if (firstName == null) + throw new ArgumentNullException("firstName is a required property for Person and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + FirstName = firstName; + LastName = lastName; + Type = type; + } + + /// + /// Gets or Sets FirstName + /// + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("$_type")] + public string Type { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Person {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Person + /// + public class PersonJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string firstName = default; + string lastName = default; + string type = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "firstName": + firstName = reader.GetString(); + break; + case "lastName": + lastName = reader.GetString(); + break; + case "$_type": + type = reader.GetString(); + break; + default: + break; + } + } + } + + return new Person(firstName, lastName, type); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Person person, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("firstName", person.FirstName); + writer.WriteString("lastName", person.LastName); + writer.WriteString("$_type", person.Type); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..96a7d12b5154 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,38 @@ + + + + true + net7.0 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + enable + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md new file mode 100644 index 000000000000..c518eef7b016 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md @@ -0,0 +1,176 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net7.0', + 'validatable=true', + 'nullableReferenceTypes=true', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + 'packageTags=', + 'packageTitle=OpenAPI Library' +) -join "," + +$global = @( + 'apiDocs=true', + 'modelDocs=true', + 'apiTests=true', + 'modelTests=true' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "github.com" ` + --git-repo-id "GIT_REPO_ID" ` + --git-user-id "GIT_USER_ID" ` + --release-note "Minor update" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.ListWithHttpInfoAsync("todo"); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace Org.OpenAPITools.Rest.DefaultApi. + Or provide your own class by using the generic ConfigureApi method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later + + +## Documentation for Authorization + +All endpoints do not require authorization. + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## Api Information +- appName: Example +- appVersion: 1.0.0 +- appDescription: No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: +- supportingFiles: +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: true +- modelDocs: true +- apiTests: true +- modelTests: true +- withXml: + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: +- apiName: Api +- caseInsensitiveResponseHeaders: +- conditionalSerialization: false +- disallowAdditionalPropertiesIfNotPresent: false +- gitHost: github.com +- gitRepoId: GIT_REPO_ID +- gitUserId: GIT_USER_ID +- hideGenerationTimestamp: true +- interfacePrefix: I +- library: generichost +- licenseId: +- modelPropertyNaming: +- netCoreProjectFile: false +- nonPublicApi: false +- nullableReferenceTypes: true +- optionalAssemblyInfo: +- optionalEmitDefaultValues: false +- optionalMethodArgument: true +- optionalProjectFile: +- packageAuthors: OpenAPI +- packageCompany: OpenAPI +- packageCopyright: No Copyright +- packageDescription: A library generated from a OpenAPI doc +- packageGuid: {321C8C3F-0156-40C1-AE42-D59761FB9B6C} +- packageName: Org.OpenAPITools +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: net7.0 +- useCollection: false +- useDateTimeOffset: false +- useOneOfDiscriminatorLookup: false +- validatable: true + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.gitignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES new file mode 100644 index 000000000000..af3bdedb0b64 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES @@ -0,0 +1,37 @@ +.gitignore +Org.OpenAPITools.sln +README.md +appveyor.yml +docs/apis/DefaultApi.md +docs/models/Apple.md +docs/models/Banana.md +docs/models/Fruit.md +docs/scripts/git_push.ps1 +docs/scripts/git_push.sh +src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/IApi.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs +src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +src/Org.OpenAPITools/Client/ApiResponse`1.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +src/Org.OpenAPITools/Client/HostConfiguration.cs +src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs +src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +src/Org.OpenAPITools/Client/TokenBase.cs +src/Org.OpenAPITools/Client/TokenContainer`1.cs +src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs +src/Org.OpenAPITools/Model/Apple.cs +src/Org.OpenAPITools/Model/Banana.cs +src/Org.OpenAPITools/Model/Fruit.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION new file mode 100644 index 000000000000..d6b4ec4aa783 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/Org.OpenAPITools.sln b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/Org.OpenAPITools.sln new file mode 100644 index 000000000000..5b15451c9dcf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/README.md new file mode 100644 index 000000000000..f9c1c7f74621 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/README.md @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/appveyor.yml b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/apis/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/apis/DefaultApi.md new file mode 100644 index 000000000000..ed95943c870a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/apis/DefaultApi.md @@ -0,0 +1,90 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**RootGet**](DefaultApi.md#rootget) | **GET** / | | + + +# **RootGet** +> Fruit RootGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class RootGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost"; + var apiInstance = new DefaultApi(config); + + try + { + Fruit result = apiInstance.RootGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.RootGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the RootGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.RootGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.RootGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**Fruit**](Fruit.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | desc | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Apple.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Apple.md new file mode 100644 index 000000000000..95f575834399 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Apple.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Banana.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Banana.md new file mode 100644 index 000000000000..c9aea6fb56c8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Banana.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Count** | **decimal** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Fruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Fruit.md new file mode 100644 index 000000000000..b3bee18f7ba0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/models/Fruit.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.ps1 new file mode 100644 index 000000000000..73ed35c2bb10 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.ps1 @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "github.com", + [Parameter()][Alias("u")][String]$GitUserId = "GIT_USER_ID", + [Parameter()][Alias("r")][String]$GitRepoId = "GIT_REPO_ID", + [Parameter()][Alias("m")][string]$Message = "Minor update", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.sh b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.sh new file mode 100644 index 000000000000..882104922184 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/docs/scripts/git_push.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-GIT_USER_ID} +git_repo_id=${2:-GIT_REPO_ID} +release_note=${3:-Minor update} +git_host=${4:-github.com} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs new file mode 100644 index 000000000000..d66ca3bec96f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -0,0 +1,58 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + + }); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..4a7789959b55 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,64 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + public sealed class DefaultApiTests : ApiTestsBase + { + private readonly IApi.IDefaultApi _instance; + + public DefaultApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + + /// + /// Test RootGet + /// + [Fact (Skip = "not implemented")] + public async Task RootGetAsyncTest() + { + var response = await _instance.RootGetAsync(); + Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 000000000000..03165a8e6fcb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -0,0 +1,103 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs new file mode 100644 index 000000000000..82bd275c0903 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Apple + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Apple + //private Apple instance; + + public AppleTests() + { + // TODO uncomment below to create an instance of Apple + //instance = new Apple(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Apple + /// + [Fact] + public void AppleInstanceTest() + { + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Kind' + /// + [Fact] + public void KindTest() + { + // TODO unit test for the property 'Kind' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs new file mode 100644 index 000000000000..db7177c2d9ea --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Banana + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Banana + //private Banana instance; + + public BananaTests() + { + // TODO uncomment below to create an instance of Banana + //instance = new Banana(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Banana + /// + [Fact] + public void BananaInstanceTest() + { + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Count' + /// + [Fact] + public void CountTest() + { + // TODO unit test for the property 'Count' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs new file mode 100644 index 000000000000..11402c0eb59a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Fruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Fruit + //private Fruit instance; + + public FruitTests() + { + // TODO uncomment below to create an instance of Fruit + //instance = new Fruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Fruit + /// + [Fact] + public void FruitInstanceTest() + { + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..96b9fd0c60e9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net7.0 + false + enable + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..ec3521d2077b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,234 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Fruit?>> + Task> RootGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Fruit> + Task RootGetAsync(System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Fruit?> + Task RootGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); + } +} + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IApi.IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + Logger = logger; + HttpClient = httpClient; + } + + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + public async Task RootGetAsync(System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse result = await RootGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + + if (result.Content == null) + throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); + + return result.Content; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + public async Task RootGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse? result = null; + try + { + result = await RootGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + } + + return result != null && result.IsSuccessStatusCode + ? result.Content + : null; + } + + /// + /// Validates the request parameters + /// + /// + protected virtual void OnRootGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterRootGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorRootGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> RootGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + OnRootGet(); + + using (HttpRequestMessage request = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress!.Port; + uriBuilder.Scheme = ClientUtils.SCHEME; + uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/"; + + + + request.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + request.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) + { + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/", uriBuilder.Path)); + + string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); + + ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); + + if (apiResponse.IsSuccessStatusCode) + { + apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterRootGet(apiResponse); + } + + return apiResponse; + } + } + } + catch(Exception e) + { + OnErrorRootGet(e, "/", uriBuilder.Path); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 000000000000..038f19bcfa1a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..6ca1d86d4a35 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,52 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 000000000000..7757b89c191c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000000..f87e53e8b048 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -0,0 +1,58 @@ +using System; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health. + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The time the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The time the response was received. + /// + public DateTime ReceivedAt { get; } + + /// + /// The HttpStatusCode received. + /// + public HttpStatusCode HttpStatus { get; } + + /// + /// The path requested. + /// + public string PathFormat { get; } + + /// + /// The elapsed time from request to response. + /// + public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + + /// + /// The path + /// + public string Path { get; } + + /// + /// The event args used to track server health. + /// + /// + /// + /// + /// + /// + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) + { + RequestedAt = requestedAt; + ReceivedAt = receivedAt; + HttpStatus = httpStatus; + PathFormat = pathFormat; + Path = path; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs new file mode 100644 index 000000000000..75c47ec63e96 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -0,0 +1,109 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// The deserialized content + /// + public T? Content { get; internal set; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The raw data + /// + public string RawContent { get; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + public ApiResponse(System.Net.Http.HttpResponseMessage response, string rawContent) + { + StatusCode = response.StatusCode; + Headers = response.Headers; + IsSuccessStatusCode = response.IsSuccessStatusCode; + ReasonPhrase = response.ReasonPhrase; + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..f8e5e299afa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,279 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is System.Collections.ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "http://localhost"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "http"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = ""; + + /// + /// The host of the API + /// + public const string HOST = "localhost"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 000000000000..85093b0c1fee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 000000000000..3b409a01d26e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000000..d31b408d40b2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,76 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs new file mode 100644 index 000000000000..5bf702060e0d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides hosting configuration for Org.OpenAPITools + /// + public class HostConfiguration + where TDefaultApi : class, IApi.IDefaultApi + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new AppleJsonConverter()); + _jsonOptions.Converters.Add(new BananaJsonConverter()); + _jsonOptions.Converters.Add(new FruitJsonConverter()); + _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); + _services.AddSingleton(); + _services.AddTransient(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients + ( + Action? client = null, Action? builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000000..0184d9ad9446 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs new file mode 100644 index 000000000000..fdf3252b9014 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -0,0 +1,49 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Threading.Channels; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Channel AvailableTokens { get; } + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens = Channel.CreateBounded(options); + + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null) + => await AvailableTokens.Reader.ReadAsync(cancellation.GetValueOrDefault()).ConfigureAwait(false); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenBase.cs new file mode 100644 index 000000000000..0faa2977dcf0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenBase.cs @@ -0,0 +1,71 @@ +// + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs new file mode 100644 index 000000000000..3fba287ad9d3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs @@ -0,0 +1,37 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs new file mode 100644 index 000000000000..322e27b931cc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -0,0 +1,44 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Collections.Generic; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 000000000000..8421965e83e0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,77 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + => ConfigureApi(builder); + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 000000000000..6df2d995e4df --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,79 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circiut breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 000000000000..600e947355b8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,101 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TDefaultApi : class, IApi.IDefaultApi + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs new file mode 100644 index 000000000000..a5ddaf33aa6f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs @@ -0,0 +1,155 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Apple + /// + public partial class Apple : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// kind + [JsonConstructor] + public Apple(string kind) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (kind == null) + throw new ArgumentNullException("kind is a required property for Apple and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Kind = kind; + } + + /// + /// Gets or Sets Kind + /// + [JsonPropertyName("kind")] + public string Kind { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Apple {\n"); + sb.Append(" Kind: ").Append(Kind).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Apple + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string kind = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "kind": + kind = reader.GetString(); + break; + default: + break; + } + } + } + + return new Apple(kind); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("kind", apple.Kind); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs new file mode 100644 index 000000000000..28086e043b33 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs @@ -0,0 +1,155 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Banana + /// + public partial class Banana : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// count + [JsonConstructor] + public Banana(decimal count) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (count == null) + throw new ArgumentNullException("count is a required property for Banana and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Count = count; + } + + /// + /// Gets or Sets Count + /// + [JsonPropertyName("count")] + public decimal Count { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Banana {\n"); + sb.Append(" Count: ").Append(Count).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Banana + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal count = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "count": + count = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Banana(count); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("count", banana.Count); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs new file mode 100644 index 000000000000..67a7458d3205 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs @@ -0,0 +1,175 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Fruit + /// + public partial class Fruit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// color + [JsonConstructor] + public Fruit(Apple apple, Banana banana, string color) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException("color is a required property for Fruit and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Apple = Apple; + Banana = Banana; + Color = color; + } + + /// + /// Gets or Sets Apple + /// + public Apple? Apple { get; set; } + + /// + /// Gets or Sets Banana + /// + public Banana? Banana { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Fruit {\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Fruit + /// + public class FruitJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Fruit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Utf8JsonReader appleReader = reader; + bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple? apple); + + Utf8JsonReader bananaReader = reader; + bool bananaDeserialized = Client.ClientUtils.TryDeserialize(ref bananaReader, options, out Banana? banana); + + string color = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "color": + color = reader.GetString(); + break; + default: + break; + } + } + } + + return new Fruit(apple, banana, color); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", fruit.Color); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..96a7d12b5154 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,38 @@ + + + + true + net7.0 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + enable + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md new file mode 100644 index 000000000000..2a488472b78b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md @@ -0,0 +1,176 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net7.0', + 'validatable=true', + 'nullableReferenceTypes=true', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + 'packageTags=', + 'packageTitle=OpenAPI Library' +) -join "," + +$global = @( + 'apiDocs=true', + 'modelDocs=true', + 'apiTests=true', + 'modelTests=true' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "github.com" ` + --git-repo-id "GIT_REPO_ID" ` + --git-user-id "GIT_USER_ID" ` + --release-note "Minor update" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.RootGetWithHttpInfoAsync("todo"); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace Org.OpenAPITools.Rest.DefaultApi. + Or provide your own class by using the generic ConfigureApi method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later + + +## Documentation for Authorization + +All endpoints do not require authorization. + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## Api Information +- appName: fruity +- appVersion: 0.0.1 +- appDescription: No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: +- supportingFiles: +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: true +- modelDocs: true +- apiTests: true +- modelTests: true +- withXml: + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: +- apiName: Api +- caseInsensitiveResponseHeaders: +- conditionalSerialization: false +- disallowAdditionalPropertiesIfNotPresent: false +- gitHost: github.com +- gitRepoId: GIT_REPO_ID +- gitUserId: GIT_USER_ID +- hideGenerationTimestamp: true +- interfacePrefix: I +- library: generichost +- licenseId: +- modelPropertyNaming: +- netCoreProjectFile: false +- nonPublicApi: false +- nullableReferenceTypes: true +- optionalAssemblyInfo: +- optionalEmitDefaultValues: false +- optionalMethodArgument: true +- optionalProjectFile: +- packageAuthors: OpenAPI +- packageCompany: OpenAPI +- packageCopyright: No Copyright +- packageDescription: A library generated from a OpenAPI doc +- packageGuid: {321C8C3F-0156-40C1-AE42-D59761FB9B6C} +- packageName: Org.OpenAPITools +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: net7.0 +- useCollection: false +- useDateTimeOffset: false +- useOneOfDiscriminatorLookup: false +- validatable: true + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.gitignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES new file mode 100644 index 000000000000..af3bdedb0b64 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES @@ -0,0 +1,37 @@ +.gitignore +Org.OpenAPITools.sln +README.md +appveyor.yml +docs/apis/DefaultApi.md +docs/models/Apple.md +docs/models/Banana.md +docs/models/Fruit.md +docs/scripts/git_push.ps1 +docs/scripts/git_push.sh +src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/IApi.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs +src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +src/Org.OpenAPITools/Client/ApiResponse`1.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +src/Org.OpenAPITools/Client/HostConfiguration.cs +src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs +src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +src/Org.OpenAPITools/Client/TokenBase.cs +src/Org.OpenAPITools/Client/TokenContainer`1.cs +src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs +src/Org.OpenAPITools/Model/Apple.cs +src/Org.OpenAPITools/Model/Banana.cs +src/Org.OpenAPITools/Model/Fruit.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION new file mode 100644 index 000000000000..d6b4ec4aa783 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/Org.OpenAPITools.sln b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/Org.OpenAPITools.sln new file mode 100644 index 000000000000..5b15451c9dcf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/README.md new file mode 100644 index 000000000000..f9c1c7f74621 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/README.md @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/appveyor.yml b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/apis/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/apis/DefaultApi.md new file mode 100644 index 000000000000..ed95943c870a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/apis/DefaultApi.md @@ -0,0 +1,90 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**RootGet**](DefaultApi.md#rootget) | **GET** / | | + + +# **RootGet** +> Fruit RootGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class RootGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost"; + var apiInstance = new DefaultApi(config); + + try + { + Fruit result = apiInstance.RootGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.RootGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the RootGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.RootGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.RootGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**Fruit**](Fruit.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | desc | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Apple.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Apple.md new file mode 100644 index 000000000000..95f575834399 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Apple.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Banana.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Banana.md new file mode 100644 index 000000000000..c9aea6fb56c8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Banana.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Count** | **decimal** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Fruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Fruit.md new file mode 100644 index 000000000000..b3bee18f7ba0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/models/Fruit.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.ps1 new file mode 100644 index 000000000000..73ed35c2bb10 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.ps1 @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "github.com", + [Parameter()][Alias("u")][String]$GitUserId = "GIT_USER_ID", + [Parameter()][Alias("r")][String]$GitRepoId = "GIT_REPO_ID", + [Parameter()][Alias("m")][string]$Message = "Minor update", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.sh b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.sh new file mode 100644 index 000000000000..882104922184 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/docs/scripts/git_push.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-GIT_USER_ID} +git_repo_id=${2:-GIT_REPO_ID} +release_note=${3:-Minor update} +git_host=${4:-github.com} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs new file mode 100644 index 000000000000..d66ca3bec96f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -0,0 +1,58 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + + }); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..4a7789959b55 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,64 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + public sealed class DefaultApiTests : ApiTestsBase + { + private readonly IApi.IDefaultApi _instance; + + public DefaultApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + + /// + /// Test RootGet + /// + [Fact (Skip = "not implemented")] + public async Task RootGetAsyncTest() + { + var response = await _instance.RootGetAsync(); + Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 000000000000..03165a8e6fcb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -0,0 +1,103 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.IApi; +using Org.OpenAPITools.Extensions; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs new file mode 100644 index 000000000000..82bd275c0903 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Apple + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Apple + //private Apple instance; + + public AppleTests() + { + // TODO uncomment below to create an instance of Apple + //instance = new Apple(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Apple + /// + [Fact] + public void AppleInstanceTest() + { + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Kind' + /// + [Fact] + public void KindTest() + { + // TODO unit test for the property 'Kind' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs new file mode 100644 index 000000000000..db7177c2d9ea --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Banana + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Banana + //private Banana instance; + + public BananaTests() + { + // TODO uncomment below to create an instance of Banana + //instance = new Banana(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Banana + /// + [Fact] + public void BananaInstanceTest() + { + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Count' + /// + [Fact] + public void CountTest() + { + // TODO unit test for the property 'Count' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs new file mode 100644 index 000000000000..11402c0eb59a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -0,0 +1,69 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Fruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Fruit + //private Fruit instance; + + public FruitTests() + { + // TODO uncomment below to create an instance of Fruit + //instance = new Fruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Fruit + /// + [Fact] + public void FruitInstanceTest() + { + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..96b9fd0c60e9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net7.0 + false + enable + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..ec3521d2077b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,234 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Fruit?>> + Task> RootGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Fruit> + Task RootGetAsync(System.Threading.CancellationToken? cancellationToken = null); + + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse<Fruit?> + Task RootGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null); + } +} + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IApi.IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + Logger = logger; + HttpClient = httpClient; + } + + /// + /// Logs the api response + /// + /// + protected virtual void OnApiResponded(ApiResponseEventArgs args) + { + Logger.LogInformation("{0,-9} | {1} | {3}", (args.ReceivedAt - args.RequestedAt).TotalSeconds, args.HttpStatus, args.Path); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + public async Task RootGetAsync(System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse result = await RootGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + + if (result.Content == null) + throw new ApiException(result.ReasonPhrase, result.StatusCode, result.RawContent); + + return result.Content; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + public async Task RootGetOrDefaultAsync(System.Threading.CancellationToken? cancellationToken = null) + { + ApiResponse? result = null; + try + { + result = await RootGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + } + + return result != null && result.IsSuccessStatusCode + ? result.Content + : null; + } + + /// + /// Validates the request parameters + /// + /// + protected virtual void OnRootGet() + { + return; + } + + /// + /// Processes the server response + /// + /// + protected virtual void AfterRootGet(ApiResponse apiResponse) + { + } + + /// + /// Processes the server response + /// + /// + /// + /// + protected virtual void OnErrorRootGet(Exception exception, string pathFormat, string path) + { + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> RootGetWithHttpInfoAsync(System.Threading.CancellationToken? cancellationToken = null) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + OnRootGet(); + + using (HttpRequestMessage request = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress!.Port; + uriBuilder.Scheme = ClientUtils.SCHEME; + uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/"; + + + + request.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + request.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) + { + OnApiResponded(new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/", uriBuilder.Path)); + + string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); + + ApiResponse apiResponse = new ApiResponse(responseMessage, responseContent); + + if (apiResponse.IsSuccessStatusCode) + { + apiResponse.Content = JsonSerializer.Deserialize(apiResponse.RawContent, _jsonSerializerOptions); + AfterRootGet(apiResponse); + } + + return apiResponse; + } + } + } + catch(Exception e) + { + OnErrorRootGet(e, "/", uriBuilder.Path); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 000000000000..038f19bcfa1a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.IApi +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..6ca1d86d4a35 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,52 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 000000000000..7757b89c191c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi.IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi.IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000000..f87e53e8b048 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -0,0 +1,58 @@ +using System; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health. + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The time the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The time the response was received. + /// + public DateTime ReceivedAt { get; } + + /// + /// The HttpStatusCode received. + /// + public HttpStatusCode HttpStatus { get; } + + /// + /// The path requested. + /// + public string PathFormat { get; } + + /// + /// The elapsed time from request to response. + /// + public TimeSpan ToTimeSpan => this.ReceivedAt - this.RequestedAt; + + /// + /// The path + /// + public string Path { get; } + + /// + /// The event args used to track server health. + /// + /// + /// + /// + /// + /// + public ApiResponseEventArgs(DateTime requestedAt, DateTime receivedAt, HttpStatusCode httpStatus, string pathFormat, string path) + { + RequestedAt = requestedAt; + ReceivedAt = receivedAt; + HttpStatus = httpStatus; + PathFormat = pathFormat; + Path = path; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs new file mode 100644 index 000000000000..75c47ec63e96 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -0,0 +1,109 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// The deserialized content + /// + public T? Content { get; internal set; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The raw data + /// + public string RawContent { get; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + public ApiResponse(System.Net.Http.HttpResponseMessage response, string rawContent) + { + StatusCode = response.StatusCode; + Headers = response.Headers; + IsSuccessStatusCode = response.IsSuccessStatusCode; + ReasonPhrase = response.ReasonPhrase; + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..f8e5e299afa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,279 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is System.Collections.ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "http://localhost"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "http"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = ""; + + /// + /// The host of the API + /// + public const string HOST = "localhost"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 000000000000..85093b0c1fee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 000000000000..3b409a01d26e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,71 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000000..d31b408d40b2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,76 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + public static readonly string[] FORMATS = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in FORMATS) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString(FORMATS[0], CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs new file mode 100644 index 000000000000..5bf702060e0d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides hosting configuration for Org.OpenAPITools + /// + public class HostConfiguration + where TDefaultApi : class, IApi.IDefaultApi + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new AppleJsonConverter()); + _jsonOptions.Converters.Add(new BananaJsonConverter()); + _jsonOptions.Converters.Add(new FruitJsonConverter()); + _services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions)); + _services.AddSingleton(); + _services.AddTransient(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients + ( + Action? client = null, Action? builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000000..0184d9ad9446 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs new file mode 100644 index 000000000000..fdf3252b9014 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -0,0 +1,49 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Threading.Channels; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Channel AvailableTokens { get; } + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens = Channel.CreateBounded(options); + + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null) + => await AvailableTokens.Reader.ReadAsync(cancellation.GetValueOrDefault()).ConfigureAwait(false); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenBase.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenBase.cs new file mode 100644 index 000000000000..0faa2977dcf0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenBase.cs @@ -0,0 +1,71 @@ +// + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs new file mode 100644 index 000000000000..3fba287ad9d3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenContainer`1.cs @@ -0,0 +1,37 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs new file mode 100644 index 000000000000..322e27b931cc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -0,0 +1,44 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Collections.Generic; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken? cancellation = null); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 000000000000..8421965e83e0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,77 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + => ConfigureApi(builder); + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action> options) + => ConfigureApi(builder, options); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 000000000000..6df2d995e4df --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,79 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circiut breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 000000000000..600e947355b8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,101 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services) + { + HostConfiguration config = new HostConfiguration(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + where TDefaultApi : class, IApi.IDefaultApi + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action> options) + { + HostConfiguration config = new HostConfiguration(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + where TDefaultApi : class, IApi.IDefaultApi + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs new file mode 100644 index 000000000000..a5ddaf33aa6f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs @@ -0,0 +1,155 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Apple + /// + public partial class Apple : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// kind + [JsonConstructor] + public Apple(string kind) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (kind == null) + throw new ArgumentNullException("kind is a required property for Apple and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Kind = kind; + } + + /// + /// Gets or Sets Kind + /// + [JsonPropertyName("kind")] + public string Kind { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Apple {\n"); + sb.Append(" Kind: ").Append(Kind).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Apple + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + string kind = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "kind": + kind = reader.GetString(); + break; + default: + break; + } + } + } + + return new Apple(kind); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("kind", apple.Kind); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs new file mode 100644 index 000000000000..28086e043b33 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs @@ -0,0 +1,155 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Banana + /// + public partial class Banana : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// count + [JsonConstructor] + public Banana(decimal count) + { +#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (count == null) + throw new ArgumentNullException("count is a required property for Banana and cannot be null."); + +#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' +#pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Count = count; + } + + /// + /// Gets or Sets Count + /// + [JsonPropertyName("count")] + public decimal Count { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Banana {\n"); + sb.Append(" Count: ").Append(Count).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Banana + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + decimal count = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "count": + count = reader.GetInt32(); + break; + default: + break; + } + } + } + + return new Banana(count); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteNumber("count", banana.Count); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs new file mode 100644 index 000000000000..0d3fac5f905c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs @@ -0,0 +1,200 @@ +// +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Fruit + /// + public partial class Fruit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// color + [JsonConstructor] + public Fruit(Apple apple, string color) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Apple = apple; + Color = color; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// color + [JsonConstructor] + public Fruit(Banana banana, string color) + { + #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + if (color == null) + throw new ArgumentNullException(nameof(Color)); + + #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' + #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' + + Banana = banana; + Color = color; + } + + /// + /// Gets or Sets Apple + /// + public Apple? Apple { get; set; } + + /// + /// Gets or Sets Banana + /// + public Banana? Banana { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Fruit {\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type Fruit + /// + public class FruitJsonConverter : JsonConverter + { + /// + /// A Json reader. + /// + /// + /// + /// + /// + /// + public override Fruit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + int currentDepth = reader.CurrentDepth; + + if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = reader.TokenType; + + Utf8JsonReader appleReader = reader; + bool appleDeserialized = Client.ClientUtils.TryDeserialize(ref appleReader, options, out Apple? apple); + + Utf8JsonReader bananaReader = reader; + bool bananaDeserialized = Client.ClientUtils.TryDeserialize(ref bananaReader, options, out Banana? banana); + + string color = default; + + while (reader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) + break; + + if (reader.TokenType == JsonTokenType.PropertyName && currentDepth == reader.CurrentDepth - 1) + { + string? propertyName = reader.GetString(); + reader.Read(); + + switch (propertyName) + { + case "color": + color = reader.GetString(); + break; + default: + break; + } + } + } + + if (appleDeserialized) + return new Fruit(apple, color); + + if (bananaDeserialized) + return new Fruit(banana, color); + + throw new JsonException(); + } + + /// + /// A Json writer + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString("color", fruit.Color); + + writer.WriteEndObject(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..96a7d12b5154 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,38 @@ + + + + true + net7.0 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + enable + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md new file mode 100644 index 000000000000..2a488472b78b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md @@ -0,0 +1,176 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net7.0', + 'validatable=true', + 'nullableReferenceTypes=true', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + 'packageTags=', + 'packageTitle=OpenAPI Library' +) -join "," + +$global = @( + 'apiDocs=true', + 'modelDocs=true', + 'apiTests=true', + 'modelTests=true' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "github.com" ` + --git-repo-id "GIT_REPO_ID" ` + --git-user-id "GIT_USER_ID" ` + --release-note "Minor update" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse foo = await api.RootGetWithHttpInfoAsync("todo"); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace Org.OpenAPITools.Rest.DefaultApi. + Or provide your own class by using the generic ConfigureApi method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later +- [Polly](https://www.nuget.org/packages/Polly/) - 7.2.3 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later + + +## Documentation for Authorization + +All endpoints do not require authorization. + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + +## Api Information +- appName: fruity +- appVersion: 0.0.1 +- appDescription: No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: +- supportingFiles: +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: true +- modelDocs: true +- apiTests: true +- modelTests: true +- withXml: + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: +- apiName: Api +- caseInsensitiveResponseHeaders: +- conditionalSerialization: false +- disallowAdditionalPropertiesIfNotPresent: false +- gitHost: github.com +- gitRepoId: GIT_REPO_ID +- gitUserId: GIT_USER_ID +- hideGenerationTimestamp: true +- interfacePrefix: I +- library: generichost +- licenseId: +- modelPropertyNaming: +- netCoreProjectFile: false +- nonPublicApi: false +- nullableReferenceTypes: true +- optionalAssemblyInfo: +- optionalEmitDefaultValues: false +- optionalMethodArgument: true +- optionalProjectFile: +- packageAuthors: OpenAPI +- packageCompany: OpenAPI +- packageCopyright: No Copyright +- packageDescription: A library generated from a OpenAPI doc +- packageGuid: {321C8C3F-0156-40C1-AE42-D59761FB9B6C} +- packageName: Org.OpenAPITools +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: net7.0 +- useCollection: false +- useDateTimeOffset: false +- useOneOfDiscriminatorLookup: false +- validatable: true + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project.