diff --git a/.github/workflows/samples-dotnet10.yaml b/.github/workflows/samples-dotnet10.yaml index 81e0ca2fcc2f..cd1dba3fa9a0 100644 --- a/.github/workflows/samples-dotnet10.yaml +++ b/.github/workflows/samples-dotnet10.yaml @@ -23,6 +23,7 @@ jobs: fail-fast: false matrix: sample: + - samples/client/petstore/csharp/generichost/latest/AnnotatedEnum - samples/client/petstore/csharp/generichost/latest/ComposedEnum - samples/client/petstore/csharp/generichost/latest/InlineEnumAnyOf - samples/client/petstore/csharp/generichost/latest/Tags diff --git a/bin/configs/csharp-generichost-latest-annotatedEnum.yaml b/bin/configs/csharp-generichost-latest-annotatedEnum.yaml new file mode 100644 index 000000000000..e1c0bd55541c --- /dev/null +++ b/bin/configs/csharp-generichost-latest-annotatedEnum.yaml @@ -0,0 +1,10 @@ +# for csharp generichost - OAS 3.1 annotated enum with const + deprecated +generatorName: csharp +outputDir: samples/client/petstore/csharp/generichost/latest/AnnotatedEnum +inputSpec: modules/openapi-generator/src/test/resources/3_1/simplifyOneOfAnyOf_test.yaml +templateDir: modules/openapi-generator/src/main/resources/csharp +additionalProperties: + packageGuid: '{A2B4C6D8-1234-5678-9ABC-DEF012345678}' + modelPropertySorting: alphabetical + operationParameterSorting: alphabetical +validateSpec: false diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java index f79dc954e119..0b5f7f16850e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java @@ -1626,6 +1626,7 @@ protected Schema processSimplifyOneOfEnum(Schema schema) { */ protected Schema simplifyComposedSchemaWithEnums(Schema schema, List subSchemas, String composedType) { Map enumValues = new LinkedHashMap<>(); + Map deprecatedValues = new LinkedHashMap<>(); if(schema.getTypes() != null && schema.getTypes().size() > 1) { // we cannot handle enums with multiple types @@ -1646,10 +1647,15 @@ protected Schema simplifyComposedSchemaWithEnums(Schema schema, List sub Schema subSchema = ModelUtils.getReferencedSchema(openAPI, (Schema) item); - // Check if this sub-schema has an enum (with one or more values) - if (subSchema.getEnum() == null || subSchema.getEnum().isEmpty()) { + // Check if this sub-schema has an enum or const value (OAS 3.1 uses const for single-value enums) + boolean definesEnum = ModelUtils.hasEnum(subSchema); + if (!definesEnum && subSchema.getConst() == null) { return schema; } + // If const is present but enum is not, treat const as a single enum value + List subSchemaEnumValues = definesEnum + ? subSchema.getEnum() + : Arrays.asList(subSchema.getConst()); // Ensure all sub-schemas have the same type (if type is specified) if(subSchema.getTypes() != null && subSchema.getTypes().size() > 1) { @@ -1664,8 +1670,9 @@ protected Schema simplifyComposedSchemaWithEnums(Schema schema, List sub return schema; } } + boolean subSchemaDeprecated = Boolean.TRUE.equals(subSchema.getDeprecated()); // Add all enum values from this sub-schema to our collection - if(subSchema.getEnum().size() == 1) { + if(subSchemaEnumValues.size() == 1) { String description = subSchema.getTitle() == null ? "" : subSchema.getTitle(); if(subSchema.getDescription() != null) { if(!description.isEmpty()) { @@ -1673,16 +1680,18 @@ protected Schema simplifyComposedSchemaWithEnums(Schema schema, List sub } description += subSchema.getDescription(); } - enumValues.put(subSchema.getEnum().get(0), description); + enumValues.put(subSchemaEnumValues.get(0), description); + deprecatedValues.put(subSchemaEnumValues.get(0), subSchemaDeprecated); } else { - for(Object e: subSchema.getEnum()) { + for(Object e: subSchemaEnumValues) { enumValues.put(e, ""); + deprecatedValues.put(e, subSchemaDeprecated); } } } - return createSimplifiedEnumSchema(schema, enumValues, schemaType, composedType); + return createSimplifiedEnumSchema(schema, enumValues, deprecatedValues, schemaType, composedType); } @@ -1691,11 +1700,12 @@ protected Schema simplifyComposedSchemaWithEnums(Schema schema, List sub * * @param originalSchema Original schema to modify * @param enumValues Collected enum values + * @param deprecatedValues Per-value deprecated flags (aligned with enumValues key order) * @param schemaType Consistent type across sub-schemas * @param composedType Type of composed schema being simplified * @return Simplified enum schema */ - protected Schema createSimplifiedEnumSchema(Schema originalSchema, Map enumValues, String schemaType, String composedType) { + protected Schema createSimplifiedEnumSchema(Schema originalSchema, Map enumValues, Map deprecatedValues, String schemaType, String composedType) { // Clear the composed schema type if ("oneOf".equals(composedType)) { originalSchema.setOneOf(null); @@ -1713,6 +1723,10 @@ protected Schema createSimplifiedEnumSchema(Schema originalSchema, Map(enumValues.values())); } + if (deprecatedValues != null && deprecatedValues.values().stream().anyMatch(Boolean.TRUE::equals)) { + // preserve per-value deprecated flags from OAS 3.1 oneOf/anyOf + const sub-schemas + originalSchema.addExtension("x-enum-deprecated", new ArrayList<>(deprecatedValues.values())); + } LOGGER.debug("Simplified {} with enum sub-schemas to single enum: {}", composedType, originalSchema); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java index a512e736e29e..24a554b926bf 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java @@ -1568,9 +1568,16 @@ public void testOpenAPINormalizerSimplifyOneOfAnyOf31Spec() { assertEquals(schema14.getType(), null); Schema schema16 = openAPI.getComponents().getSchemas().get("TypeIntegerWithOneOf"); - assertEquals(schema16.getOneOf().size(),3); - assertEquals(((Schema) schema16.getOneOf().get(0)).getConst(), 1); - assertEquals(((Schema) schema16.getOneOf().get(0)).getDeprecated(), true); + // After normalization, oneOf with const values should be simplified to enum + assertEquals(schema16.getOneOf(), null); + assertEquals(schema16.getEnum().size(), 3); + assertEquals(schema16.getEnum().get(0), 1); + // per-value deprecated flags from oneOf sub-schemas should be preserved as x-enum-deprecated + List enumDeprecated = (List) schema16.getExtensions().get("x-enum-deprecated"); + assertEquals(enumDeprecated.size(), 3); + assertEquals(enumDeprecated.get(0), Boolean.TRUE); + assertEquals(enumDeprecated.get(1), Boolean.FALSE); + assertEquals(enumDeprecated.get(2), Boolean.FALSE); Schema schema18 = openAPI.getComponents().getSchemas().get("OneOfNullAndRef3"); // original oneOf removed and simplified to just $ref (oneOf sub-schema) instead diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.gitignore b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.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/generichost/latest/AnnotatedEnum/.openapi-generator-ignore b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.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/generichost/latest/AnnotatedEnum/.openapi-generator/FILES b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator/FILES new file mode 100644 index 000000000000..d24be74d0bd8 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator/FILES @@ -0,0 +1,65 @@ +.gitignore +Org.OpenAPITools.sln +README.md +api/openapi.yaml +appveyor.yml +docs/apis/DefaultApi.md +docs/models/AnyOfStringArrayOfString.md +docs/models/Number.md +docs/models/Number2.md +docs/models/OneOfNullAndRef.md +docs/models/OneOfNullAndRef2.md +docs/models/OneOfNullAndRef3.md +docs/models/OneOfNullableTest.md +docs/models/Parent.md +docs/models/ParentWithOneOfProperty.md +docs/models/ParentWithPluralOneOfProperty.md +docs/models/ParentWithPluralOneOfPropertyNumber.md +docs/models/PropertiesWithAnyOf.md +docs/models/SingleAnyOfTest.md +docs/models/TypeIntegerWithOneOf.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/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +src/Org.OpenAPITools/Client/ExceptionEventArgs.cs +src/Org.OpenAPITools/Client/FileParameter.cs +src/Org.OpenAPITools/Client/HostConfiguration.cs +src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs +src/Org.OpenAPITools/Client/Option.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/AnyOfStringArrayOfString.cs +src/Org.OpenAPITools/Model/Number.cs +src/Org.OpenAPITools/Model/Number2.cs +src/Org.OpenAPITools/Model/OneOfNullAndRef.cs +src/Org.OpenAPITools/Model/OneOfNullAndRef2.cs +src/Org.OpenAPITools/Model/OneOfNullAndRef3.cs +src/Org.OpenAPITools/Model/OneOfNullableTest.cs +src/Org.OpenAPITools/Model/Parent.cs +src/Org.OpenAPITools/Model/ParentWithOneOfProperty.cs +src/Org.OpenAPITools/Model/ParentWithPluralOneOfProperty.cs +src/Org.OpenAPITools/Model/ParentWithPluralOneOfPropertyNumber.cs +src/Org.OpenAPITools/Model/PropertiesWithAnyOf.cs +src/Org.OpenAPITools/Model/SingleAnyOfTest.cs +src/Org.OpenAPITools/Model/TypeIntegerWithOneOf.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator/VERSION b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator/VERSION new file mode 100644 index 000000000000..186c33c96ed8 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.24.0-SNAPSHOT diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/Org.OpenAPITools.sln b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/Org.OpenAPITools.sln new file mode 100644 index 000000000000..1dae1ae95a13 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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", "{A2B4C6D8-1234-5678-9ABC-DEF012345678}" +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 + {A2B4C6D8-1234-5678-9ABC-DEF012345678}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2B4C6D8-1234-5678-9ABC-DEF012345678}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2B4C6D8-1234-5678-9ABC-DEF012345678}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2B4C6D8-1234-5678-9ABC-DEF012345678}.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/generichost/latest/AnnotatedEnum/README.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/README.md new file mode 100644 index 000000000000..334b39306832 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/README.md @@ -0,0 +1,2 @@ +# Created with Openapi Generator +See the project's [REAMDE](src/Org.OpenAPITools/README.md) \ No newline at end of file diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/api/openapi.yaml b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/api/openapi.yaml new file mode 100644 index 000000000000..da6dae64572d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/api/openapi.yaml @@ -0,0 +1,138 @@ +openapi: 3.1.0 +info: + license: + name: MIT + title: Example + version: 1.0.0 +servers: +- url: http://api.example.xyz/v1 +paths: + /person/display/{personId}: + get: + operationId: list + parameters: + - description: The id of the person to retrieve + explode: false + in: path + name: personId + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AnyOfTest" + description: OK +components: + schemas: + AnyOfTest: + description: to test anyOf + nullable: true + type: string + OneOfTest: + description: to test oneOf + nullable: true + type: integer + OneOfTest2: + description: to test oneOf + nullable: true + type: string + OneOfNullableTest: + description: to test oneOf nullable + nullable: true + oneOf: + - type: integer + - description: to test oneOf + nullable: true + type: string + SingleAnyOfTest: + description: to test anyOf (enum string only) + enum: + - A + - B + type: string + Parent: + properties: + number: + $ref: "#/components/schemas/Number" + ParentWithOneOfProperty: + properties: + number: + $ref: "#/components/schemas/Number" + ParentWithPluralOneOfProperty: + properties: + number: + $ref: "#/components/schemas/ParentWithPluralOneOfProperty_number" + PropertiesWithAnyOf: + additionalProperties: {} + properties: + anyof_nullable_string: + description: to test oneOf + nullable: true + type: string + anyof_nullable_number: + nullable: true + type: number + Number: + enum: + - one + - two + - three + type: string + Number2: + enum: + - one + - two + type: string + AnyOfStringArrayOfString: + anyOf: + - description: to test oneOf + nullable: true + type: string + - items: + description: to test oneOf + nullable: true + type: string + type: array + default: null + AnyOfAnyType: + example: null + default: null + OneOfAnyType: + example: null + default: null + TypeIntegerWithOneOf: + enum: + - 1 + - 2 + - 4 + format: int32 + type: integer + x-enum-descriptions: + - ITEM A - This permission is for item A. + - ITEM B - This permission is for item B. + - ITEM C - This permission is for item C. + x-enum-deprecated: + - true + - false + - false + OneOfNullAndRef: + allOf: + - $ref: "#/components/schemas/Parent" + nullable: true + OneOfNullAndRef2: + allOf: + - $ref: "#/components/schemas/Parent" + nullable: true + OneOfNullAndRef3: + allOf: + - $ref: "#/components/schemas/Parent" + nullable: true + ParentWithPluralOneOfProperty_number: + oneOf: + - $ref: "#/components/schemas/Number" + - $ref: "#/components/schemas/Number2" + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/appveyor.yml b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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/generichost/latest/AnnotatedEnum/docs/apis/DefaultApi.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/apis/DefaultApi.md new file mode 100644 index 000000000000..b4bfeaf2061d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/apis/DefaultApi.md @@ -0,0 +1,42 @@ +# 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** +> string List (string personId) + + + + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **personId** | **string** | The id of the person to retrieve | | + +### Return type + +**string** + +### 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/generichost/latest/AnnotatedEnum/docs/models/AnyOfStringArrayOfString.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/AnyOfStringArrayOfString.md new file mode 100644 index 000000000000..53b7952e6e92 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/AnyOfStringArrayOfString.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.AnyOfStringArrayOfString + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number.md new file mode 100644 index 000000000000..6c94ed1b4785 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.Number + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number2.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number2.md new file mode 100644 index 000000000000..daa98df5bbda --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Number2.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.Number2 + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef.md new file mode 100644 index 000000000000..3faabbe53c52 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.OneOfNullAndRef + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Number** | | [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/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef2.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef2.md new file mode 100644 index 000000000000..137986a4d9d8 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef2.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.OneOfNullAndRef2 + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Number** | | [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/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef3.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef3.md new file mode 100644 index 000000000000..f94b4fde8504 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullAndRef3.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.OneOfNullAndRef3 + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Number** | | [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/generichost/latest/AnnotatedEnum/docs/models/OneOfNullableTest.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullableTest.md new file mode 100644 index 000000000000..713677ad6817 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/OneOfNullableTest.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.OneOfNullableTest +to test oneOf nullable + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Parent.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Parent.md new file mode 100644 index 000000000000..dac496df7fd5 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/Parent.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Parent + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Number** | | [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/generichost/latest/AnnotatedEnum/docs/models/ParentWithOneOfProperty.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithOneOfProperty.md new file mode 100644 index 000000000000..ab66fe7eebda --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithOneOfProperty.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ParentWithOneOfProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Number** | | [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/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfProperty.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfProperty.md new file mode 100644 index 000000000000..22b6f8cb5a44 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfProperty.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ParentWithPluralOneOfProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | [**ParentWithPluralOneOfPropertyNumber**](ParentWithPluralOneOfPropertyNumber.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/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfPropertyNumber.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfPropertyNumber.md new file mode 100644 index 000000000000..4ded0536a96f --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/ParentWithPluralOneOfPropertyNumber.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.ParentWithPluralOneOfPropertyNumber + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/PropertiesWithAnyOf.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/PropertiesWithAnyOf.md new file mode 100644 index 000000000000..10a4fe8430ea --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/PropertiesWithAnyOf.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.PropertiesWithAnyOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**AnyofNullableNumber** | **decimal** | | [optional] +**AnyofNullableString** | **string** | to test oneOf | [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/generichost/latest/AnnotatedEnum/docs/models/SingleAnyOfTest.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/SingleAnyOfTest.md new file mode 100644 index 000000000000..aa665ed90f2e --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/SingleAnyOfTest.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.SingleAnyOfTest +to test anyOf (enum string only) + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/TypeIntegerWithOneOf.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/TypeIntegerWithOneOf.md new file mode 100644 index 000000000000..404382bb64c9 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/models/TypeIntegerWithOneOf.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.TypeIntegerWithOneOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/scripts/git_push.ps1 new file mode 100644 index 000000000000..73ed35c2bb10 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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/generichost/latest/AnnotatedEnum/docs/scripts/git_push.sh b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/docs/scripts/git_push.sh new file mode 100644 index 000000000000..882104922184 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs new file mode 100644 index 000000000000..5dd80394d3fc --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..4fb5a11d1267 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,64 @@ +/* + * 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.Api; + + +/* ********************************************************************************* +* 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 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); + var model = response.Ok(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 000000000000..f408496be456 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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.Api; +using Org.OpenAPITools.Extensions; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => + { + + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder([]).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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/AnyOfStringArrayOfStringTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/AnyOfStringArrayOfStringTests.cs new file mode 100644 index 000000000000..be2e472566f2 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/AnyOfStringArrayOfStringTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AnyOfStringArrayOfString + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AnyOfStringArrayOfStringTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AnyOfStringArrayOfString + //private AnyOfStringArrayOfString instance; + + public AnyOfStringArrayOfStringTests() + { + // TODO uncomment below to create an instance of AnyOfStringArrayOfString + //instance = new AnyOfStringArrayOfString(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AnyOfStringArrayOfString + /// + [Fact] + public void AnyOfStringArrayOfStringInstanceTest() + { + // TODO uncomment below to test "IsType" AnyOfStringArrayOfString + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/Number2Tests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/Number2Tests.cs new file mode 100644 index 000000000000..5bc6adf1cc2f --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/Number2Tests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Number2 + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class Number2Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for Number2 + //private Number2 instance; + + public Number2Tests() + { + // TODO uncomment below to create an instance of Number2 + //instance = new Number2(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Number2 + /// + [Fact] + public void Number2InstanceTest() + { + // TODO uncomment below to test "IsType" Number2 + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/NumberTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/NumberTests.cs new file mode 100644 index 000000000000..50e1a5452a5a --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/NumberTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Number + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NumberTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Number + //private Number instance; + + public NumberTests() + { + // TODO uncomment below to create an instance of Number + //instance = new Number(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Number + /// + [Fact] + public void NumberInstanceTest() + { + // TODO uncomment below to test "IsType" Number + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef2Tests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef2Tests.cs new file mode 100644 index 000000000000..4b8cd5f4751c --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef2Tests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OneOfNullAndRef2 + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OneOfNullAndRef2Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for OneOfNullAndRef2 + //private OneOfNullAndRef2 instance; + + public OneOfNullAndRef2Tests() + { + // TODO uncomment below to create an instance of OneOfNullAndRef2 + //instance = new OneOfNullAndRef2(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OneOfNullAndRef2 + /// + [Fact] + public void OneOfNullAndRef2InstanceTest() + { + // TODO uncomment below to test "IsType" OneOfNullAndRef2 + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef3Tests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef3Tests.cs new file mode 100644 index 000000000000..1a52139dab04 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRef3Tests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OneOfNullAndRef3 + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OneOfNullAndRef3Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for OneOfNullAndRef3 + //private OneOfNullAndRef3 instance; + + public OneOfNullAndRef3Tests() + { + // TODO uncomment below to create an instance of OneOfNullAndRef3 + //instance = new OneOfNullAndRef3(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OneOfNullAndRef3 + /// + [Fact] + public void OneOfNullAndRef3InstanceTest() + { + // TODO uncomment below to test "IsType" OneOfNullAndRef3 + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRefTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRefTests.cs new file mode 100644 index 000000000000..27678c54f680 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullAndRefTests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OneOfNullAndRef + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OneOfNullAndRefTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OneOfNullAndRef + //private OneOfNullAndRef instance; + + public OneOfNullAndRefTests() + { + // TODO uncomment below to create an instance of OneOfNullAndRef + //instance = new OneOfNullAndRef(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OneOfNullAndRef + /// + [Fact] + public void OneOfNullAndRefInstanceTest() + { + // TODO uncomment below to test "IsType" OneOfNullAndRef + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullableTestTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullableTestTests.cs new file mode 100644 index 000000000000..0226527a4741 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/OneOfNullableTestTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OneOfNullableTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OneOfNullableTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OneOfNullableTest + //private OneOfNullableTest instance; + + public OneOfNullableTestTests() + { + // TODO uncomment below to create an instance of OneOfNullableTest + //instance = new OneOfNullableTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OneOfNullableTest + /// + [Fact] + public void OneOfNullableTestInstanceTest() + { + // TODO uncomment below to test "IsType" OneOfNullableTest + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentTests.cs new file mode 100644 index 000000000000..0a4375cd0ee1 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentTests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Parent + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Parent + //private Parent instance; + + public ParentTests() + { + // TODO uncomment below to create an instance of Parent + //instance = new Parent(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Parent + /// + [Fact] + public void ParentInstanceTest() + { + // TODO uncomment below to test "IsType" Parent + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithOneOfPropertyTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithOneOfPropertyTests.cs new file mode 100644 index 000000000000..5384d5aa97b1 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithOneOfPropertyTests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ParentWithOneOfProperty + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentWithOneOfPropertyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentWithOneOfProperty + //private ParentWithOneOfProperty instance; + + public ParentWithOneOfPropertyTests() + { + // TODO uncomment below to create an instance of ParentWithOneOfProperty + //instance = new ParentWithOneOfProperty(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentWithOneOfProperty + /// + [Fact] + public void ParentWithOneOfPropertyInstanceTest() + { + // TODO uncomment below to test "IsType" ParentWithOneOfProperty + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyNumberTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyNumberTests.cs new file mode 100644 index 000000000000..34b2f91e59c6 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyNumberTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ParentWithPluralOneOfPropertyNumber + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentWithPluralOneOfPropertyNumberTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentWithPluralOneOfPropertyNumber + //private ParentWithPluralOneOfPropertyNumber instance; + + public ParentWithPluralOneOfPropertyNumberTests() + { + // TODO uncomment below to create an instance of ParentWithPluralOneOfPropertyNumber + //instance = new ParentWithPluralOneOfPropertyNumber(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentWithPluralOneOfPropertyNumber + /// + [Fact] + public void ParentWithPluralOneOfPropertyNumberInstanceTest() + { + // TODO uncomment below to test "IsType" ParentWithPluralOneOfPropertyNumber + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyTests.cs new file mode 100644 index 000000000000..d025eb0f17c3 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/ParentWithPluralOneOfPropertyTests.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 Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ParentWithPluralOneOfProperty + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentWithPluralOneOfPropertyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentWithPluralOneOfProperty + //private ParentWithPluralOneOfProperty instance; + + public ParentWithPluralOneOfPropertyTests() + { + // TODO uncomment below to create an instance of ParentWithPluralOneOfProperty + //instance = new ParentWithPluralOneOfProperty(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentWithPluralOneOfProperty + /// + [Fact] + public void ParentWithPluralOneOfPropertyInstanceTest() + { + // TODO uncomment below to test "IsType" ParentWithPluralOneOfProperty + //Assert.IsType(instance); + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/PropertiesWithAnyOfTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/PropertiesWithAnyOfTests.cs new file mode 100644 index 000000000000..4b8dd1bf13ee --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/PropertiesWithAnyOfTests.cs @@ -0,0 +1,74 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing PropertiesWithAnyOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PropertiesWithAnyOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for PropertiesWithAnyOf + //private PropertiesWithAnyOf instance; + + public PropertiesWithAnyOfTests() + { + // TODO uncomment below to create an instance of PropertiesWithAnyOf + //instance = new PropertiesWithAnyOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PropertiesWithAnyOf + /// + [Fact] + public void PropertiesWithAnyOfInstanceTest() + { + // TODO uncomment below to test "IsType" PropertiesWithAnyOf + //Assert.IsType(instance); + } + + /// + /// Test the property 'AnyofNullableNumber' + /// + [Fact] + public void AnyofNullableNumberTest() + { + // TODO unit test for the property 'AnyofNullableNumber' + } + + /// + /// Test the property 'AnyofNullableString' + /// + [Fact] + public void AnyofNullableStringTest() + { + // TODO unit test for the property 'AnyofNullableString' + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/SingleAnyOfTestTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/SingleAnyOfTestTests.cs new file mode 100644 index 000000000000..ab83e1dfea22 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/SingleAnyOfTestTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing SingleAnyOfTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SingleAnyOfTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SingleAnyOfTest + //private SingleAnyOfTest instance; + + public SingleAnyOfTestTests() + { + // TODO uncomment below to create an instance of SingleAnyOfTest + //instance = new SingleAnyOfTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SingleAnyOfTest + /// + [Fact] + public void SingleAnyOfTestInstanceTest() + { + // TODO uncomment below to test "IsType" SingleAnyOfTest + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/TypeIntegerWithOneOfTests.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/TypeIntegerWithOneOfTests.cs new file mode 100644 index 000000000000..f49cb305c255 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Model/TypeIntegerWithOneOfTests.cs @@ -0,0 +1,56 @@ +/* + * 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.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing TypeIntegerWithOneOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TypeIntegerWithOneOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TypeIntegerWithOneOf + //private TypeIntegerWithOneOf instance; + + public TypeIntegerWithOneOfTests() + { + // TODO uncomment below to create an instance of TypeIntegerWithOneOf + //instance = new TypeIntegerWithOneOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TypeIntegerWithOneOf + /// + [Fact] + public void TypeIntegerWithOneOfInstanceTest() + { + // TODO uncomment below to test "IsType" TypeIntegerWithOneOf + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..77eea8e35f6a --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,21 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net10.0 + false + enable + false + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..52d29376389a --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,383 @@ +// +/* + * 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.Collections.ObjectModel; +using System.Net; +using System.IO; +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 System.Diagnostics.CodeAnalysis; + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// The class containing the events + /// + DefaultApiEvents Events { get; } + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <> + Task ListAsync(string personId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <?> + Task ListOrDefaultAsync(string personId, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IListApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class DefaultApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnList; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorList; + + internal void ExecuteOnList(DefaultApi.ListApiResponse apiResponse) + { + OnList?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorList(Exception exception) + { + OnErrorList?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class DefaultApi : IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public DefaultApiEvents Events { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DefaultApiEvents defaultApiEvents) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = defaultApiEvents; + } + + partial void FormatList(ref string personId); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateList(string personId) + { + if (personId == null) + throw new ArgumentNullException(nameof(personId)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterListDefaultImplementation(IListApiResponse apiResponseLocalVar, string personId) + { + bool suppressDefaultLog = false; + AfterList(ref suppressDefaultLog, apiResponseLocalVar, personId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterList(ref bool suppressDefaultLog, IListApiResponse apiResponseLocalVar, string personId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorListDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string personId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorList(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, personId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorList(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string personId); + + /// + /// + /// + /// The id of the person to retrieve + /// Cancellation Token to cancel the request. + /// <> + public async Task ListOrDefaultAsync(string personId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await ListAsync(personId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// 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 = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateList(personId); + + FormatList(ref personId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/person/display/{personId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/person/display/{personId}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpersonId%7D", Uri.EscapeDataString(personId.ToString())); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + ListApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/person/display/{personId}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterListDefaultImplementation(apiResponseLocalVar, personId); + + Events.ExecuteOnList(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorListDefaultImplementation(e, "/person/display/{personId}", uriBuilderLocalVar.Path, personId); + Events.ExecuteOnErrorList(e); + throw; + } + } + + /// + /// The + /// + public partial class ListApiResponse : Org.OpenAPITools.Client.ApiResponse, IListApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public ListApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public ListApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public string? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out string? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 000000000000..65c41d0633ba --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,24 @@ +/* + * 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.Net.Http; + +namespace Org.OpenAPITools.Api +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..eaf62115550f --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 000000000000..6a6cadccdb3d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiFactory.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 Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000000..3f062c6e5399 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -0,0 +1,33 @@ +/* + * 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; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponse`1.cs new file mode 100644 index 000000000000..78160f0c716c --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -0,0 +1,219 @@ +// +/* + * 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.Diagnostics.CodeAnalysis; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the api response + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The raw binary stream (only set for binary responses) + /// + System.IO.Stream? ContentStream { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the api response + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The headers contained in the api response related to the content + /// + System.Net.Http.Headers.HttpContentHeaders ContentHeaders { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the api response + /// + string? ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri? RequestUri { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data + /// + public string RawContent { get; protected set; } + + /// + /// The raw binary stream (only set for binary responses) + /// + public System.IO.Stream? ContentStream { get; protected set; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The headers contained in the api response related to the content + /// + public System.Net.Http.Headers.HttpContentHeaders ContentHeaders { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri? RequestUri { get; } + + /// + /// The + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + ContentHeaders = httpResponseMessage.Content.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + ContentHeaders = httpResponseMessage.Content.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + ContentStream = contentStream; + RawContent = string.Empty; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + } + + /// + /// An interface for responses of type + /// + /// + public interface IOk : IApiResponse + { + /// + /// Deserializes the response if the response is Ok + /// + /// + TType Ok(); + + /// + /// Returns true if the response is Ok and the deserialized response is not null + /// + /// + /// + bool TryOk([NotNullWhen(true)]out TType? result); + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..37bfa30f4c64 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,366 @@ +/* + * 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.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Org.OpenAPITools.Model; +using System.Runtime.CompilerServices; +using System.Net.Http.Headers; + +[assembly: InternalsVisibleTo("Org.OpenAPITools.Test")] + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + + /// + /// 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, [global::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, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// 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 DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean + ? "true" + : "false"; + if (obj is Number number) + return NumberValueConverter.ToJsonValue(number); + if (obj is Number2 number2) + return Number2ValueConverter.ToJsonValue(number2); + if (obj is SingleAnyOfTest singleAnyOfTest) + return SingleAnyOfTestValueConverter.ToJsonValue(singleAnyOfTest); + if (obj is TypeIntegerWithOneOf typeIntegerWithOneOf) + return TypeIntegerWithOneOfValueConverter.ToJsonValue(typeIntegerWithOneOf).ToString(); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::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); + } + + + + /// + /// 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. + /// + /// The accepts array to select from. + /// The Accept header values to use. + public static IEnumerable SelectHeaderAcceptArray(string[] accepts) + { + if (accepts.Length == 0) + return []; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return [MediaTypeWithQualityHeaderValue.Parse("application/json")]; + + return accepts.Select(MediaTypeWithQualityHeaderValue.Parse); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// 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"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (localVarJsonPropertyName != null && localVarJsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// Determines if the provided header is a content header + /// + /// The header to check + /// True if a content header; False otherwise + public static bool IsContentHeader(string header) + { + return ContentHeaders.Contains(header.ToLowerInvariant()); + } + + /// + /// The collection of content headers as per + /// https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.headers + /// + private static readonly string[] ContentHeaders = new String[] + { + "allow", + "content-encoding", + "content-disposition", + "content-language", + "content-length", + "content-location", + "content-md5", + "content-range", + "content-type", + "expires", + "last-modified" + }; + + /// + /// 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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 000000000000..2cd377673b91 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,28 @@ +// +/* + * 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.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(); + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..671c407f55a0 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.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 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 DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly 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 (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..ae9a253b5aa1 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * 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 DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? 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 (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 000000000000..79fb8600e4be --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,75 @@ +/* + * 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-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "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("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000000..26d8b0757ba4 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,80 @@ +/* + * 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-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "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("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs new file mode 100644 index 000000000000..a3320d0d1b82 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs @@ -0,0 +1,33 @@ +/* + * 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; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health + /// + public class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExceptionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/FileParameter.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/FileParameter.cs new file mode 100644 index 000000000000..9f2614c6f4ce --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/FileParameter.cs @@ -0,0 +1,50 @@ +// +/* + * 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 + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a file to be uploaded as part of a multipart/form-data request. + /// + public sealed class FileParameter + { + /// + /// The file content stream. + /// + public global::System.IO.Stream Content { get; } + + /// + /// The filename sent in the Content-Disposition header. + /// When null the parameter name from the spec is used as a fallback. + /// + public string? FileName { get; } + + /// + /// The MIME type sent in the Content-Type header of the part. + /// Defaults to application/octet-stream. + /// + public string ContentType { get; } + + /// + /// Creates a new . + /// + /// The file content stream. + /// Optional filename for the Content-Disposition header. + /// Optional MIME type for the Content-Type header of the part. Defaults to application/octet-stream. + public FileParameter(global::System.IO.Stream content, string? fileName = null, string contentType = "application/octet-stream") + { + Content = content; + FileName = fileName; + ContentType = contentType; + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/HostConfiguration.cs new file mode 100644 index 000000000000..66352cde017b --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -0,0 +1,176 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides hosting configuration for Org.OpenAPITools + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AnyOfStringArrayOfStringJsonConverter()); + _jsonOptions.Converters.Add(new NumberJsonConverter()); + _jsonOptions.Converters.Add(new NumberNullableJsonConverter()); + _jsonOptions.Converters.Add(new Number2JsonConverter()); + _jsonOptions.Converters.Add(new Number2NullableJsonConverter()); + _jsonOptions.Converters.Add(new OneOfNullAndRefJsonConverter()); + _jsonOptions.Converters.Add(new OneOfNullAndRef2JsonConverter()); + _jsonOptions.Converters.Add(new OneOfNullAndRef3JsonConverter()); + _jsonOptions.Converters.Add(new OneOfNullableTestJsonConverter()); + _jsonOptions.Converters.Add(new ParentJsonConverter()); + _jsonOptions.Converters.Add(new ParentWithOneOfPropertyJsonConverter()); + _jsonOptions.Converters.Add(new ParentWithPluralOneOfPropertyJsonConverter()); + _jsonOptions.Converters.Add(new ParentWithPluralOneOfPropertyNumberJsonConverter()); + _jsonOptions.Converters.Add(new PropertiesWithAnyOfJsonConverter()); + _jsonOptions.Converters.Add(new SingleAnyOfTestJsonConverter()); + _jsonOptions.Converters.Add(new SingleAnyOfTestNullableJsonConverter()); + _jsonOptions.Converters.Add(new TypeIntegerWithOneOfJsonConverter()); + _jsonOptions.Converters.Add(new TypeIntegerWithOneOfNullableJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + public HostConfiguration AddApiHttpClients(Action? builder = null) + { + return AddApiHttpClients((Action?)null, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients( + Action? client, + Action? builder = null) + { + var wrapped = client != null ? new Action((_, httpClient) => + { + client(httpClient); + }) : null; + return AddApiHttpClients(wrapped, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients( + Action? client, + Action? builder = null) + { + if (client == null) + client = (_, c) => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient("Org.OpenAPITools.Api.IDefaultApi", 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/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000000..f84b0c81cfc5 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,35 @@ +// +/* + * 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.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; + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/Option.cs new file mode 100644 index 000000000000..b3419229d654 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/Option.cs @@ -0,0 +1,53 @@ +// +/* + * 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 + + +namespace Org.OpenAPITools.Client +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs new file mode 100644 index 000000000000..0f58d97aa070 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -0,0 +1,62 @@ +// +/* + * 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; + +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 + { + /// + /// Dictionary mapping header names to channels of available tokens for rate limiting. + /// Each channel buffers tokens that have become available and are ready for use. + /// + protected internal Dictionary> AvailableTokens { get; } = new(); + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base() + { + foreach(TTokenBase token in container.Tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + global::System.Threading.Channels.BoundedChannelOptions options = new global::System.Threading.Channels.BoundedChannelOptions(container.Tokens.Count) + { + FullMode = global::System.Threading.Channels.BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, global::System.Threading.Channels.Channel.CreateBounded(options)); + + foreach (var availableToken in AvailableTokens) + foreach(TTokenBase token in container.Tokens) + { + token.TokenBecameAvailable += ((sender) => availableToken.Value.Writer.TryWrite((TTokenBase)sender)); + } + } + + /// + protected internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out global::System.Threading.Channels.Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenBase.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenBase.cs new file mode 100644 index 000000000000..7e44c07e3955 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenBase.cs @@ -0,0 +1,85 @@ +// +/* + * 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 +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private readonly object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + internal TimeSpan? Timeout { get; set; } + + /// + /// Delegate for token availability notification events. + /// + /// The token that became available. + public delegate void TokenBecameAvailableEventHandler(object sender); + + /// + /// Event raised when a rate-limited token becomes available for use. + /// + public 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 { get { lock (_nextAvailableLock) return _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 (!IsRateLimited) + TokenBecameAvailable?.Invoke(this); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenContainer`1.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenContainer`1.cs new file mode 100644 index 000000000000..77adf6a995f9 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenContainer`1.cs @@ -0,0 +1,45 @@ +// +/* + * 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.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(global::System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenProvider`1.cs new file mode 100644 index 000000000000..c66cdb4ee2a4 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -0,0 +1,32 @@ +// +/* + * 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 + { + /// + /// Gets a token asynchronously for the specified header. + /// + /// The header name to retrieve a token for. Empty string for non-API-key authentication schemes. + /// Cancellation token for the asynchronous operation. + /// A task that returns the requested token. + protected internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 000000000000..733d70fe43f1 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,59 @@ +/* + * 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; + +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) + { + 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, Action options) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 000000000000..813775e7dcf9 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/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 circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 000000000000..c7fc843b1e4d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,73 @@ +/* + * 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; + +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) + { + HostConfiguration config = new(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action options) + { + HostConfiguration config = new(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/AnyOfStringArrayOfString.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/AnyOfStringArrayOfString.cs new file mode 100644 index 000000000000..1b72efa00efc --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/AnyOfStringArrayOfString.cs @@ -0,0 +1,212 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// AnyOfStringArrayOfString + /// + public partial class AnyOfStringArrayOfString : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal AnyOfStringArrayOfString(Option @string, Option?> list) + { + StringOption = @string; + ListOption = list; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of String + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StringOption { get; private set; } + + /// + /// to test oneOf + /// + /// to test oneOf + public string? String { get { return this.StringOption.Value; } set { this.StringOption = new(value); } } + + /// + /// Used to track the state of List + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ListOption { get; private set; } + + /// + /// Gets or Sets List + /// + public List? List { get { return this.ListOption.Value; } set { this.ListOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AnyOfStringArrayOfString {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class AnyOfStringArrayOfStringJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public AnyOfStringArrayOfStringJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override AnyOfStringArrayOfString Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varString = default; + List? list = default; + + Utf8JsonReader utf8JsonReaderAnyOf = utf8JsonReader; + while (utf8JsonReaderAnyOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (utf8JsonReaderAnyOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderAnyOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderString = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderString, jsonSerializerOptions, out varString); + + Utf8JsonReader utf8JsonReaderList = utf8JsonReader; + ClientUtils.TryDeserialize?>(ref utf8JsonReaderList, jsonSerializerOptions, out list); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + Option varStringParsedValue = varString == null + ? default + : new Option(varString); + Option?> listParsedValue = list == null + ? default + : new Option?>(list); + + return new AnyOfStringArrayOfString(varStringParsedValue, listParsedValue); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AnyOfStringArrayOfString anyOfStringArrayOfString, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (anyOfStringArrayOfString.StringOption.IsSet && anyOfStringArrayOfString.StringOption.Value != null) + writer.WriteString("AnyOfStringArrayOfString", anyOfStringArrayOfString.StringOption.Value); + + if (anyOfStringArrayOfString.ListOption.IsSet && anyOfStringArrayOfString.ListOption.Value != null) + + WriteProperties(writer, anyOfStringArrayOfString, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AnyOfStringArrayOfString anyOfStringArrayOfString, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number.cs new file mode 100644 index 000000000000..330c21c74b2a --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number.cs @@ -0,0 +1,189 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines Number + /// + public enum Number + { + /// + /// Enum One for value: one + /// + One = 1, + + /// + /// Enum Two for value: two + /// + Two = 2, + + /// + /// Enum Three for value: three + /// + Three = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class NumberValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static Number FromString(string value) + { + if (value.Equals("one")) + return Number.One; + + if (value.Equals("two")) + return Number.Two; + + if (value.Equals("three")) + return Number.Three; + + throw new NotImplementedException($"Could not convert value to type Number: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static Number? FromStringOrDefault(string value) + { + if (value.Equals("one")) + return Number.One; + + if (value.Equals("two")) + return Number.Two; + + if (value.Equals("three")) + return Number.Three; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(Number value) + { + if (value == Number.One) + return "one"; + + if (value == Number.Two) + return "two"; + + if (value == Number.Three) + return "three"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class NumberJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override Number Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Number? result = rawValue == null + ? null + : NumberValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Number to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Number number, JsonSerializerOptions options) + { + writer.WriteStringValue(NumberValueConverter.ToJsonValue(number).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class NumberNullableJsonConverter : JsonConverter + { + /// + /// Returns a Number from the Json object + /// + /// + /// + /// + /// + public override Number? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Number? result = rawValue == null + ? null + : NumberValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Number to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Number? number, JsonSerializerOptions options) + { + writer.WriteStringValue(number.HasValue ? NumberValueConverter.ToJsonValue(number.Value).ToString() : "null"); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number2.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number2.cs new file mode 100644 index 000000000000..9716d178f110 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Number2.cs @@ -0,0 +1,175 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines Number2 + /// + public enum Number2 + { + /// + /// Enum One for value: one + /// + One = 1, + + /// + /// Enum Two for value: two + /// + Two = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class Number2ValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static Number2 FromString(string value) + { + if (value.Equals("one")) + return Number2.One; + + if (value.Equals("two")) + return Number2.Two; + + throw new NotImplementedException($"Could not convert value to type Number2: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static Number2? FromStringOrDefault(string value) + { + if (value.Equals("one")) + return Number2.One; + + if (value.Equals("two")) + return Number2.Two; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(Number2 value) + { + if (value == Number2.One) + return "one"; + + if (value == Number2.Two) + return "two"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class Number2JsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override Number2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Number2? result = rawValue == null + ? null + : Number2ValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Number2 to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Number2 number2, JsonSerializerOptions options) + { + writer.WriteStringValue(Number2ValueConverter.ToJsonValue(number2).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class Number2NullableJsonConverter : JsonConverter + { + /// + /// Returns a Number2 from the Json object + /// + /// + /// + /// + /// + public override Number2? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Number2? result = rawValue == null + ? null + : Number2ValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Number2 to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Number2? number2, JsonSerializerOptions options) + { + writer.WriteStringValue(number2.HasValue ? Number2ValueConverter.ToJsonValue(number2.Value).ToString() : "null"); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef.cs new file mode 100644 index 000000000000..912ed2a7f792 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// OneOfNullAndRef + /// + public partial class OneOfNullAndRef : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public OneOfNullAndRef(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public Number? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OneOfNullAndRef {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class OneOfNullAndRefJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public OneOfNullAndRefJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OneOfNullAndRef Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + string? numberRawValue = utf8JsonReader.GetString(); + if (numberRawValue != null) + number = new Option(NumberValueConverter.FromStringOrDefault(numberRawValue)); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class OneOfNullAndRef."); + + return new OneOfNullAndRef(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OneOfNullAndRef oneOfNullAndRef, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, oneOfNullAndRef, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OneOfNullAndRef oneOfNullAndRef, JsonSerializerOptions jsonSerializerOptions) + { + if (oneOfNullAndRef.NumberOption.IsSet) + { + var numberRawValue = NumberValueConverter.ToJsonValue(oneOfNullAndRef.Number!.Value); + writer.WriteString("number", numberRawValue); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef2.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef2.cs new file mode 100644 index 000000000000..d74c1a874025 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef2.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// OneOfNullAndRef2 + /// + public partial class OneOfNullAndRef2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public OneOfNullAndRef2(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public Number? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OneOfNullAndRef2 {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class OneOfNullAndRef2JsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public OneOfNullAndRef2JsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OneOfNullAndRef2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + string? numberRawValue = utf8JsonReader.GetString(); + if (numberRawValue != null) + number = new Option(NumberValueConverter.FromStringOrDefault(numberRawValue)); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class OneOfNullAndRef2."); + + return new OneOfNullAndRef2(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OneOfNullAndRef2 oneOfNullAndRef2, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, oneOfNullAndRef2, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OneOfNullAndRef2 oneOfNullAndRef2, JsonSerializerOptions jsonSerializerOptions) + { + if (oneOfNullAndRef2.NumberOption.IsSet) + { + var numberRawValue = NumberValueConverter.ToJsonValue(oneOfNullAndRef2.Number!.Value); + writer.WriteString("number", numberRawValue); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef3.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef3.cs new file mode 100644 index 000000000000..dc30a138a6e1 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullAndRef3.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// OneOfNullAndRef3 + /// + public partial class OneOfNullAndRef3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public OneOfNullAndRef3(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public Number? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OneOfNullAndRef3 {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class OneOfNullAndRef3JsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public OneOfNullAndRef3JsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OneOfNullAndRef3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + string? numberRawValue = utf8JsonReader.GetString(); + if (numberRawValue != null) + number = new Option(NumberValueConverter.FromStringOrDefault(numberRawValue)); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class OneOfNullAndRef3."); + + return new OneOfNullAndRef3(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OneOfNullAndRef3 oneOfNullAndRef3, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, oneOfNullAndRef3, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OneOfNullAndRef3 oneOfNullAndRef3, JsonSerializerOptions jsonSerializerOptions) + { + if (oneOfNullAndRef3.NumberOption.IsSet) + { + var numberRawValue = NumberValueConverter.ToJsonValue(oneOfNullAndRef3.Number!.Value); + writer.WriteString("number", numberRawValue); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullableTest.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullableTest.cs new file mode 100644 index 000000000000..2d632afcb947 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/OneOfNullableTest.cs @@ -0,0 +1,200 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// to test oneOf nullable + /// + public partial class OneOfNullableTest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + internal OneOfNullableTest(int @int) + { + Int = @int; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal OneOfNullableTest(string @string) + { + String = @string; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Int + /// + public int? Int { get; set; } + + /// + /// to test oneOf + /// + /// to test oneOf + public string? String { 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 OneOfNullableTest {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class OneOfNullableTestJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public OneOfNullableTestJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OneOfNullableTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + int? varInt = default; + string? varString = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderInt = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInt, jsonSerializerOptions, out varInt); + + Utf8JsonReader utf8JsonReaderString = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderString, jsonSerializerOptions, out varString); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + if (varInt != null) + return new OneOfNullableTest(varInt.Value); + + if (varString != null) + return new OneOfNullableTest(varString); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OneOfNullableTest oneOfNullableTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, oneOfNullableTest, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OneOfNullableTest oneOfNullableTest, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Parent.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Parent.cs new file mode 100644 index 000000000000..aa88c257aedf --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/Parent.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// Parent + /// + public partial class Parent : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public Parent(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public Number? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Parent {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class ParentJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public ParentJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Parent Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + string? numberRawValue = utf8JsonReader.GetString(); + if (numberRawValue != null) + number = new Option(NumberValueConverter.FromStringOrDefault(numberRawValue)); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class Parent."); + + return new Parent(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Parent parent, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, parent, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Parent parent, JsonSerializerOptions jsonSerializerOptions) + { + if (parent.NumberOption.IsSet) + { + var numberRawValue = NumberValueConverter.ToJsonValue(parent.Number!.Value); + writer.WriteString("number", numberRawValue); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithOneOfProperty.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithOneOfProperty.cs new file mode 100644 index 000000000000..07dafb5b44ad --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithOneOfProperty.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// ParentWithOneOfProperty + /// + public partial class ParentWithOneOfProperty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public ParentWithOneOfProperty(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public Number? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ParentWithOneOfProperty {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class ParentWithOneOfPropertyJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public ParentWithOneOfPropertyJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ParentWithOneOfProperty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + string? numberRawValue = utf8JsonReader.GetString(); + if (numberRawValue != null) + number = new Option(NumberValueConverter.FromStringOrDefault(numberRawValue)); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class ParentWithOneOfProperty."); + + return new ParentWithOneOfProperty(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ParentWithOneOfProperty parentWithOneOfProperty, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, parentWithOneOfProperty, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ParentWithOneOfProperty parentWithOneOfProperty, JsonSerializerOptions jsonSerializerOptions) + { + if (parentWithOneOfProperty.NumberOption.IsSet) + { + var numberRawValue = NumberValueConverter.ToJsonValue(parentWithOneOfProperty.Number!.Value); + writer.WriteString("number", numberRawValue); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfProperty.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfProperty.cs new file mode 100644 index 000000000000..2f55ea9f5d23 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfProperty.cs @@ -0,0 +1,181 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// ParentWithPluralOneOfProperty + /// + public partial class ParentWithPluralOneOfProperty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// number + [JsonConstructor] + public ParentWithPluralOneOfProperty(Option number = default) + { + NumberOption = number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Number + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberOption { get; private set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public ParentWithPluralOneOfPropertyNumber? Number { get { return this.NumberOption.Value; } set { this.NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ParentWithPluralOneOfProperty {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class ParentWithPluralOneOfPropertyJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public ParentWithPluralOneOfPropertyJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ParentWithPluralOneOfProperty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "number": + number = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class ParentWithPluralOneOfProperty."); + + return new ParentWithPluralOneOfProperty(number); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ParentWithPluralOneOfProperty parentWithPluralOneOfProperty, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, parentWithPluralOneOfProperty, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ParentWithPluralOneOfProperty parentWithPluralOneOfProperty, JsonSerializerOptions jsonSerializerOptions) + { + if (parentWithPluralOneOfProperty.NumberOption.IsSet && parentWithPluralOneOfProperty.Number == null) + throw new ArgumentNullException(nameof(parentWithPluralOneOfProperty.Number), "Property is required for class ParentWithPluralOneOfProperty."); + + if (parentWithPluralOneOfProperty.NumberOption.IsSet) + { + writer.WritePropertyName("number"); + JsonSerializer.Serialize(writer, parentWithPluralOneOfProperty.Number, jsonSerializerOptions); + } + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfPropertyNumber.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfPropertyNumber.cs new file mode 100644 index 000000000000..42eb5c9cd94d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/ParentWithPluralOneOfPropertyNumber.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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// ParentWithPluralOneOfPropertyNumber + /// + public partial class ParentWithPluralOneOfPropertyNumber : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + internal ParentWithPluralOneOfPropertyNumber(Number number) + { + Number = number; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal ParentWithPluralOneOfPropertyNumber(Number2 number2) + { + Number2 = number2; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Number + /// + public Number? Number { get; set; } + + /// + /// Gets or Sets Number2 + /// + public Number2? Number2 { 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 ParentWithPluralOneOfPropertyNumber {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class ParentWithPluralOneOfPropertyNumberJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public ParentWithPluralOneOfPropertyNumberJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ParentWithPluralOneOfPropertyNumber Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Number? number = default; + Number2? number2 = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderNumber = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumber, jsonSerializerOptions, out number); + + Utf8JsonReader utf8JsonReaderNumber2 = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumber2, jsonSerializerOptions, out number2); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + if (number != null) + return new ParentWithPluralOneOfPropertyNumber(number.Value); + + if (number2 != null) + return new ParentWithPluralOneOfPropertyNumber(number2.Value); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ParentWithPluralOneOfPropertyNumber parentWithPluralOneOfPropertyNumber, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, parentWithPluralOneOfPropertyNumber, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ParentWithPluralOneOfPropertyNumber parentWithPluralOneOfPropertyNumber, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/PropertiesWithAnyOf.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/PropertiesWithAnyOf.cs new file mode 100644 index 000000000000..e56da97f4a3d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/PropertiesWithAnyOf.cs @@ -0,0 +1,209 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// PropertiesWithAnyOf + /// + public partial class PropertiesWithAnyOf : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// anyofNullableNumber + /// to test oneOf + [JsonConstructor] + public PropertiesWithAnyOf(Option anyofNullableNumber = default, Option anyofNullableString = default) + { + AnyofNullableNumberOption = anyofNullableNumber; + AnyofNullableStringOption = anyofNullableString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of AnyofNullableNumber + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyofNullableNumberOption { get; private set; } + + /// + /// Gets or Sets AnyofNullableNumber + /// + [JsonPropertyName("anyof_nullable_number")] + public decimal? AnyofNullableNumber { get { return this.AnyofNullableNumberOption.Value; } set { this.AnyofNullableNumberOption = new(value); } } + + /// + /// Used to track the state of AnyofNullableString + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyofNullableStringOption { get; private set; } + + /// + /// to test oneOf + /// + /// to test oneOf + [JsonPropertyName("anyof_nullable_string")] + public string? AnyofNullableString { get { return this.AnyofNullableStringOption.Value; } set { this.AnyofNullableStringOption = new(value); } } + + /// + /// 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 PropertiesWithAnyOf {\n"); + sb.Append(" AnyofNullableNumber: ").Append(AnyofNullableNumber).Append("\n"); + sb.Append(" AnyofNullableString: ").Append(AnyofNullableString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public partial class PropertiesWithAnyOfJsonConverter : JsonConverter + { + partial void OnCreated(); + + /// + /// Initializes a new instance of the class. + /// + public PropertiesWithAnyOfJsonConverter() + { + OnCreated(); + } + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override PropertiesWithAnyOf Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option anyofNullableNumber = default; + Option anyofNullableString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "anyof_nullable_number": + anyofNullableNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "anyof_nullable_string": + anyofNullableString = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + return new PropertiesWithAnyOf(anyofNullableNumber, anyofNullableString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PropertiesWithAnyOf propertiesWithAnyOf, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, propertiesWithAnyOf, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PropertiesWithAnyOf propertiesWithAnyOf, JsonSerializerOptions jsonSerializerOptions) + { + if (propertiesWithAnyOf.AnyofNullableNumberOption.IsSet) + if (propertiesWithAnyOf.AnyofNullableNumberOption.Value != null) + writer.WriteNumber("anyof_nullable_number", propertiesWithAnyOf.AnyofNullableNumberOption.Value!.Value); + else + writer.WriteNull("anyof_nullable_number"); + + if (propertiesWithAnyOf.AnyofNullableStringOption.IsSet) + if (propertiesWithAnyOf.AnyofNullableStringOption.Value != null) + writer.WriteString("anyof_nullable_string", propertiesWithAnyOf.AnyofNullableString); + else + writer.WriteNull("anyof_nullable_string"); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/SingleAnyOfTest.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/SingleAnyOfTest.cs new file mode 100644 index 000000000000..a55596b7fa4d --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/SingleAnyOfTest.cs @@ -0,0 +1,176 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// to test anyOf (enum string only) + /// + /// to test anyOf (enum string only) + public enum SingleAnyOfTest + { + /// + /// Enum A for value: A + /// + A = 1, + + /// + /// Enum B for value: B + /// + B = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class SingleAnyOfTestValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static SingleAnyOfTest FromString(string value) + { + if (value.Equals("A")) + return SingleAnyOfTest.A; + + if (value.Equals("B")) + return SingleAnyOfTest.B; + + throw new NotImplementedException($"Could not convert value to type SingleAnyOfTest: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static SingleAnyOfTest? FromStringOrDefault(string value) + { + if (value.Equals("A")) + return SingleAnyOfTest.A; + + if (value.Equals("B")) + return SingleAnyOfTest.B; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(SingleAnyOfTest value) + { + if (value == SingleAnyOfTest.A) + return "A"; + + if (value == SingleAnyOfTest.B) + return "B"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class SingleAnyOfTestJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override SingleAnyOfTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SingleAnyOfTest? result = rawValue == null + ? null + : SingleAnyOfTestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SingleAnyOfTest to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SingleAnyOfTest singleAnyOfTest, JsonSerializerOptions options) + { + writer.WriteStringValue(SingleAnyOfTestValueConverter.ToJsonValue(singleAnyOfTest).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class SingleAnyOfTestNullableJsonConverter : JsonConverter + { + /// + /// Returns a SingleAnyOfTest from the Json object + /// + /// + /// + /// + /// + public override SingleAnyOfTest? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SingleAnyOfTest? result = rawValue == null + ? null + : SingleAnyOfTestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SingleAnyOfTest to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SingleAnyOfTest? singleAnyOfTest, JsonSerializerOptions options) + { + writer.WriteStringValue(singleAnyOfTest.HasValue ? SingleAnyOfTestValueConverter.ToJsonValue(singleAnyOfTest.Value).ToString() : "null"); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/TypeIntegerWithOneOf.cs b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/TypeIntegerWithOneOf.cs new file mode 100644 index 000000000000..d0a733fe6f9e --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Model/TypeIntegerWithOneOf.cs @@ -0,0 +1,180 @@ +// +/* + * 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 Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines TypeIntegerWithOneOf + /// + public enum TypeIntegerWithOneOf + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_4 for value: 4 + /// + NUMBER_4 = 4 + } + + /// + /// Converts to and from the JSON value + /// + public static class TypeIntegerWithOneOfValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TypeIntegerWithOneOf FromString(string value) + { + if (value.Equals((1).ToString())) + return TypeIntegerWithOneOf.NUMBER_1; + + if (value.Equals((2).ToString())) + return TypeIntegerWithOneOf.NUMBER_2; + + if (value.Equals((4).ToString())) + return TypeIntegerWithOneOf.NUMBER_4; + + throw new NotImplementedException($"Could not convert value to type TypeIntegerWithOneOf: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TypeIntegerWithOneOf? FromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return TypeIntegerWithOneOf.NUMBER_1; + + if (value.Equals((2).ToString())) + return TypeIntegerWithOneOf.NUMBER_2; + + if (value.Equals((4).ToString())) + return TypeIntegerWithOneOf.NUMBER_4; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static int ToJsonValue(TypeIntegerWithOneOf value) + { + return (int) value; + } + } + + /// + /// A Json converter for type + /// + /// + public class TypeIntegerWithOneOfJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TypeIntegerWithOneOf Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TypeIntegerWithOneOf? result = rawValue == null + ? null + : TypeIntegerWithOneOfValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TypeIntegerWithOneOf to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TypeIntegerWithOneOf typeIntegerWithOneOf, JsonSerializerOptions options) + { + writer.WriteStringValue(TypeIntegerWithOneOfValueConverter.ToJsonValue(typeIntegerWithOneOf).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TypeIntegerWithOneOfNullableJsonConverter : JsonConverter + { + /// + /// Returns a TypeIntegerWithOneOf from the Json object + /// + /// + /// + /// + /// + public override TypeIntegerWithOneOf? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TypeIntegerWithOneOf? result = rawValue == null + ? null + : TypeIntegerWithOneOfValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TypeIntegerWithOneOf to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TypeIntegerWithOneOf? typeIntegerWithOneOf, JsonSerializerOptions options) + { + writer.WriteStringValue(typeIntegerWithOneOf.HasValue ? TypeIntegerWithOneOfValueConverter.ToJsonValue(typeIntegerWithOneOf.Value).ToString() : "null"); + } + } +} diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..864c6bc3f48b --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,31 @@ + + + + true + net10.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 + false + + + + + + + + + + diff --git a/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/README.md new file mode 100644 index 000000000000..8cdfa05d13d9 --- /dev/null +++ b/samples/client/petstore/csharp/generichost/latest/AnnotatedEnum/src/Org.OpenAPITools/README.md @@ -0,0 +1,111 @@ +# Created with Openapi Generator + + +## Creating the library +Create a config.yaml file similar to what is below, then run the following powershell command to generate the library `java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate -c config.yaml` + +```yaml +generatorName: csharp +inputSpec: modules/openapi-generator/src/test/resources/3_1/simplifyOneOfAnyOf_test.yaml +outputDir: out + +# https://openapi-generator.tech/docs/generators/csharp +additionalProperties: + packageGuid: '{A2B4C6D8-1234-5678-9ABC-DEF012345678}' + +# https://openapi-generator.tech/docs/integrations/#github-integration +# gitHost: +# gitUserId: +# gitRepoId: + +# https://openapi-generator.tech/docs/globals +# globalProperties: + +# https://openapi-generator.tech/docs/customization/#inline-schema-naming +# inlineSchemaOptions: + +# https://openapi-generator.tech/docs/customization/#name-mapping +# modelNameMappings: +# nameMappings: + +# https://openapi-generator.tech/docs/customization/#openapi-normalizer +# openapiNormalizer: + +# templateDir: https://openapi-generator.tech/docs/templating/#modifying-templates + +# releaseNote: +``` + + +## Using the library in your project + +```cs +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Extensions; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + IListApiResponse apiResponse = await api.ListAsync("todo"); + string? model = apiResponse.Ok(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(client => + { + // client configuration + }, 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? + Configure Polly in the IHttpClientBuilder +- 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 partial methods in the api classes. + +## Api Information +- appName: Example +- appVersion: 1.0.0 +- appDescription: No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Build +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. + +- SDK version: 1.0.0 +- Generator version: 7.24.0-SNAPSHOT +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen