From 43a719f92bec19f20aed5f857880c63e1dff6e84 Mon Sep 17 00:00:00 2001 From: slavkor <30171206+slavkor@users.noreply.github.com> Date: Thu, 4 Jul 2024 10:12:37 +0000 Subject: [PATCH] chore: release data-link SDK --- src/.gitignore | 362 ++++++++ src/.openapi-generator-ignore | 23 + src/.openapi-generator/FILES | 39 + src/.openapi-generator/VERSION | 1 + src/Databox.sln | 27 + src/README.md | 160 ++++ src/api/openapi.yaml | 100 +++ src/appveyor.yml | 9 + src/docs/ApiResponse.md | 11 + src/docs/DefaultApi.md | 98 +++ src/docs/PayloadDataModel.md | 15 + src/docs/PayloadModel.md | 10 + src/git_push.sh | 57 ++ src/src/Databox.Test/Api/DefaultApiTests.cs | 67 ++ src/src/Databox.Test/Databox.Test.csproj | 20 + .../Databox.Test/Model/ApiResponseTests.cs | 75 ++ .../Model/PayloadDataModelTests.cs | 111 +++ .../Databox.Test/Model/PayloadModelTests.cs | 66 ++ src/src/Databox/Api/DefaultApi.cs | 401 +++++++++ src/src/Databox/Client/ApiClient.cs | 788 ++++++++++++++++++ src/src/Databox/Client/ApiException.cs | 68 ++ src/src/Databox/Client/ApiResponse.cs | 166 ++++ src/src/Databox/Client/ClientUtils.cs | 247 ++++++ src/src/Databox/Client/Configuration.cs | 612 ++++++++++++++ src/src/Databox/Client/ExceptionFactory.cs | 22 + src/src/Databox/Client/FileParameter.cs | 80 ++ src/src/Databox/Client/GlobalConfiguration.cs | 67 ++ src/src/Databox/Client/IApiAccessor.cs | 37 + src/src/Databox/Client/IAsynchronousClient.cs | 100 +++ .../Databox/Client/IReadableConfiguration.cs | 141 ++++ src/src/Databox/Client/ISynchronousClient.cs | 93 +++ src/src/Databox/Client/Multimap.cs | 295 +++++++ .../Databox/Client/OpenAPIDateConverter.cs | 29 + src/src/Databox/Client/RequestOptions.cs | 74 ++ src/src/Databox/Client/RetryConfiguration.cs | 31 + .../Databox/Client/WebRequestPathBuilder.cs | 53 ++ src/src/Databox/Databox.csproj | 35 + .../Databox/Model/AbstractOpenAPISchema.cs | 76 ++ src/src/Databox/Model/ApiResponse.cs | 92 ++ src/src/Databox/Model/PayloadDataModel.cs | 143 ++++ src/src/Databox/Model/PayloadModel.cs | 83 ++ src/test/test1 | 0 src/test2/test2 | 0 43 files changed, 4984 insertions(+) create mode 100644 src/.gitignore create mode 100644 src/.openapi-generator-ignore create mode 100644 src/.openapi-generator/FILES create mode 100644 src/.openapi-generator/VERSION create mode 100644 src/Databox.sln create mode 100644 src/README.md create mode 100644 src/api/openapi.yaml create mode 100644 src/appveyor.yml create mode 100644 src/docs/ApiResponse.md create mode 100644 src/docs/DefaultApi.md create mode 100644 src/docs/PayloadDataModel.md create mode 100644 src/docs/PayloadModel.md create mode 100644 src/git_push.sh create mode 100644 src/src/Databox.Test/Api/DefaultApiTests.cs create mode 100644 src/src/Databox.Test/Databox.Test.csproj create mode 100644 src/src/Databox.Test/Model/ApiResponseTests.cs create mode 100644 src/src/Databox.Test/Model/PayloadDataModelTests.cs create mode 100644 src/src/Databox.Test/Model/PayloadModelTests.cs create mode 100644 src/src/Databox/Api/DefaultApi.cs create mode 100644 src/src/Databox/Client/ApiClient.cs create mode 100644 src/src/Databox/Client/ApiException.cs create mode 100644 src/src/Databox/Client/ApiResponse.cs create mode 100644 src/src/Databox/Client/ClientUtils.cs create mode 100644 src/src/Databox/Client/Configuration.cs create mode 100644 src/src/Databox/Client/ExceptionFactory.cs create mode 100644 src/src/Databox/Client/FileParameter.cs create mode 100644 src/src/Databox/Client/GlobalConfiguration.cs create mode 100644 src/src/Databox/Client/IApiAccessor.cs create mode 100644 src/src/Databox/Client/IAsynchronousClient.cs create mode 100644 src/src/Databox/Client/IReadableConfiguration.cs create mode 100644 src/src/Databox/Client/ISynchronousClient.cs create mode 100644 src/src/Databox/Client/Multimap.cs create mode 100644 src/src/Databox/Client/OpenAPIDateConverter.cs create mode 100644 src/src/Databox/Client/RequestOptions.cs create mode 100644 src/src/Databox/Client/RetryConfiguration.cs create mode 100644 src/src/Databox/Client/WebRequestPathBuilder.cs create mode 100644 src/src/Databox/Databox.csproj create mode 100644 src/src/Databox/Model/AbstractOpenAPISchema.cs create mode 100644 src/src/Databox/Model/ApiResponse.cs create mode 100644 src/src/Databox/Model/PayloadDataModel.cs create mode 100644 src/src/Databox/Model/PayloadModel.cs delete mode 100644 src/test/test1 delete mode 100644 src/test2/test2 diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..1ee5385 --- /dev/null +++ b/src/.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/src/.openapi-generator-ignore b/src/.openapi-generator-ignore new file mode 100644 index 0000000..7484ee5 --- /dev/null +++ b/src/.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/src/.openapi-generator/FILES b/src/.openapi-generator/FILES new file mode 100644 index 0000000..6145832 --- /dev/null +++ b/src/.openapi-generator/FILES @@ -0,0 +1,39 @@ +.gitignore +.openapi-generator-ignore +Databox.sln +README.md +api/openapi.yaml +appveyor.yml +docs/ApiResponse.md +docs/DefaultApi.md +docs/PayloadDataModel.md +docs/PayloadModel.md +git_push.sh +src/Databox.Test/Api/DefaultApiTests.cs +src/Databox.Test/Databox.Test.csproj +src/Databox.Test/Model/ApiResponseTests.cs +src/Databox.Test/Model/PayloadDataModelTests.cs +src/Databox.Test/Model/PayloadModelTests.cs +src/Databox/Api/DefaultApi.cs +src/Databox/Client/ApiClient.cs +src/Databox/Client/ApiException.cs +src/Databox/Client/ApiResponse.cs +src/Databox/Client/ClientUtils.cs +src/Databox/Client/Configuration.cs +src/Databox/Client/ExceptionFactory.cs +src/Databox/Client/FileParameter.cs +src/Databox/Client/GlobalConfiguration.cs +src/Databox/Client/IApiAccessor.cs +src/Databox/Client/IAsynchronousClient.cs +src/Databox/Client/IReadableConfiguration.cs +src/Databox/Client/ISynchronousClient.cs +src/Databox/Client/Multimap.cs +src/Databox/Client/OpenAPIDateConverter.cs +src/Databox/Client/RequestOptions.cs +src/Databox/Client/RetryConfiguration.cs +src/Databox/Client/WebRequestPathBuilder.cs +src/Databox/Databox.csproj +src/Databox/Model/AbstractOpenAPISchema.cs +src/Databox/Model/ApiResponse.cs +src/Databox/Model/PayloadDataModel.cs +src/Databox/Model/PayloadModel.cs diff --git a/src/.openapi-generator/VERSION b/src/.openapi-generator/VERSION new file mode 100644 index 0000000..93c8dda --- /dev/null +++ b/src/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.6.0 diff --git a/src/Databox.sln b/src/Databox.sln new file mode 100644 index 0000000..8dd544d --- /dev/null +++ b/src/Databox.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}") = "Databox", "src\Databox\Databox.csproj", "{D544B3EB-FF32-49CB-8A1D-8BD16C86A4EA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Databox.Test", "src\Databox.Test\Databox.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 + {D544B3EB-FF32-49CB-8A1D-8BD16C86A4EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D544B3EB-FF32-49CB-8A1D-8BD16C86A4EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D544B3EB-FF32-49CB-8A1D-8BD16C86A4EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D544B3EB-FF32-49CB-8A1D-8BD16C86A4EA}.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/src/README.md b/src/README.md new file mode 100644 index 0000000..1259055 --- /dev/null +++ b/src/README.md @@ -0,0 +1,160 @@ +# Databox - the C# library for the Static OpenAPI document of Push API resource + +Push API resources Open API documentation + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0 +- SDK version: 0.0.2 +- Generator version: 7.6.0 +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen + + +## Frameworks supported + + +## Dependencies + +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.2 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +Install-Package System.ComponentModel.Annotations +``` + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using Databox.Api; +using Databox.Client; +using Databox.Model; +``` + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out Databox.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` + +### Connections +Each ApiClass (properly the ApiClient inside it) will create an instance of HttpClient. It will use that for the entire lifecycle and dispose it when called the Dispose method. + +To better manager the connections it's a common practice to reuse the HttpClient and HttpClientHandler (see [here](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net) for details). To use your own HttpClient instance just pass it to the ApiClass constructor. + +```csharp +HttpClientHandler yourHandler = new HttpClientHandler(); +HttpClient yourHttpClient = new HttpClient(yourHandler); +var api = new YourApiClass(yourHttpClient, yourHandler); +``` + +If you want to use an HttpClient and don't have access to the handler, for example in a DI context in Asp.net Core when using IHttpClientFactory. + +```csharp +HttpClient yourHttpClient = new HttpClient(); +var api = new YourApiClass(yourHttpClient); +``` +You'll loose some configuration settings, the features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. You need to either manually handle those in your setup of the HttpClient or they won't be available. + +Here an example of DI setup in a sample web project: + +```csharp +services.AddHttpClient(httpClient => + new PetApi(httpClient)); +``` + + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using System.Net.Http; +using Databox.Api; +using Databox.Client; +using Databox.Model; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration config = new Configuration(); + config.BasePath = "http://localhost:8080/q/openapi"; + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new DefaultApi(httpClient, config, httpClientHandler); + var payloadModel = new PayloadModel?(); // PayloadModel? | (optional) + + try + { + apiInstance.RootPost(payloadModel); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.RootPost: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:8080/q/openapi* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**RootPost**](docs/DefaultApi.md#rootpost) | **POST** / | + + + +## Documentation for Models + + - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.PayloadDataModel](docs/PayloadDataModel.md) + - [Model.PayloadModel](docs/PayloadModel.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### basicAuth + +- **Type**: HTTP basic authentication + diff --git a/src/api/openapi.yaml b/src/api/openapi.yaml new file mode 100644 index 0000000..a7b357d --- /dev/null +++ b/src/api/openapi.yaml @@ -0,0 +1,100 @@ +openapi: 3.0.3 +info: + description: Push API resources Open API documentation + title: Static OpenAPI document of Push API resource + version: "1.0" +servers: +- description: Dev mode server description + url: http://localhost:8080/q/openapi +paths: + /: + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PayloadModel' + responses: + "200": + content: + application/json: + example: + status: OK + message: "" + description: OK + "400": + content: + application/json: + example: + status: Bad Request + message: Bad request - Exceeded request count limit! + description: Bad Request + "401": + content: + application/json: + example: + status: Unauthorized + message: Unauthorized - Invalid token! + description: Unauthorized + "500": + content: + application/json: + example: + status: Internal Server Error + message: An unhandled exception occurred while processing your request! + description: Internal Server Error +components: + schemas: + PayloadModel: + example: + data: + - $: 123.4 + date: 2021-03-01 00:00:00 + : Organic + unit: USD + - $: 123.4 + periodFrom: 2021-03-01 00:00:00 + periodTo: 2021-03-16 00:00:00 + : Organic + unit: USD + properties: + data: + items: + $ref: '#/components/schemas/PayloadDataModel' + type: array + type: object + PayloadDataModel: + properties: + $: + description: example metric name would be '$sales' + type: number + : + description: example dimension would be 'channel' + type: string + unit: + type: string + periodFrom: + description: required if date not provided + type: string + periodTo: + description: required if date not provided + type: string + date: + description: required periods not provided + type: string + required: + - "$," + - date + type: object + ApiResponse: + properties: + status: + type: string + message: + type: string + type: object + securitySchemes: + basicAuth: + scheme: basic + type: http + diff --git a/src/appveyor.yml b/src/appveyor.yml new file mode 100644 index 0000000..ecdee7b --- /dev/null +++ b/src/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\Databox\Databox.csproj -o ../../output -c Release --no-build diff --git a/src/docs/ApiResponse.md b/src/docs/ApiResponse.md new file mode 100644 index 0000000..61a0934 --- /dev/null +++ b/src/docs/ApiResponse.md @@ -0,0 +1,11 @@ +# Databox.Model.ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Status** | **string** | | [optional] +**Message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/src/docs/DefaultApi.md b/src/docs/DefaultApi.md new file mode 100644 index 0000000..6d306c4 --- /dev/null +++ b/src/docs/DefaultApi.md @@ -0,0 +1,98 @@ +# Databox.Api.DefaultApi + +All URIs are relative to *http://localhost:8080/q/openapi* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**RootPost**](DefaultApi.md#rootpost) | **POST** / | | + + +# **RootPost** +> void RootPost (PayloadModel? payloadModel = null) + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using System.Net.Http; +using Databox.Api; +using Databox.Client; +using Databox.Model; + +namespace Example +{ + public class RootPostExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost:8080/q/openapi"; + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new DefaultApi(httpClient, config, httpClientHandler); + var payloadModel = new PayloadModel?(); // PayloadModel? | (optional) + + try + { + apiInstance.RootPost(payloadModel); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.RootPost: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the RootPostWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.RootPostWithHttpInfo(payloadModel); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.RootPostWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **payloadModel** | [**PayloadModel?**](PayloadModel?.md) | | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | +| **400** | Bad Request | - | +| **401** | Unauthorized | - | +| **500** | Internal Server Error | - | + +[[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/src/docs/PayloadDataModel.md b/src/docs/PayloadDataModel.md new file mode 100644 index 0000000..7f876df --- /dev/null +++ b/src/docs/PayloadDataModel.md @@ -0,0 +1,15 @@ +# Databox.Model.PayloadDataModel + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MetricName** | **decimal** | example metric name would be '$sales' | [optional] +**DimensionName** | **string** | example dimension would be 'channel' | [optional] +**Unit** | **string** | | [optional] +**PeriodFrom** | **string** | required if date not provided | [optional] +**PeriodTo** | **string** | required if date not provided | [optional] +**Date** | **string** | required periods not provided | + +[[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/src/docs/PayloadModel.md b/src/docs/PayloadModel.md new file mode 100644 index 0000000..35487d8 --- /dev/null +++ b/src/docs/PayloadModel.md @@ -0,0 +1,10 @@ +# Databox.Model.PayloadModel + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Data** | [**List<PayloadDataModel>**](PayloadDataModel.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/src/git_push.sh b/src/git_push.sh new file mode 100644 index 0000000..f53a75d --- /dev/null +++ b/src/git_push.sh @@ -0,0 +1,57 @@ +#!/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_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/src/src/Databox.Test/Api/DefaultApiTests.cs b/src/src/Databox.Test/Api/DefaultApiTests.cs new file mode 100644 index 0000000..c7ca94d --- /dev/null +++ b/src/src/Databox.Test/Api/DefaultApiTests.cs @@ -0,0 +1,67 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using Xunit; + +using Databox.Client; +using Databox.Api; +// uncomment below to import models +//using Databox.Model; + +namespace Databox.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class DefaultApiTests : IDisposable + { + private DefaultApi instance; + + public DefaultApiTests() + { + instance = new DefaultApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DefaultApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' DefaultApi + //Assert.IsType(instance); + } + + /// + /// Test RootPost + /// + [Fact] + public void RootPostTest() + { + // TODO uncomment below to test the method and replace null with proper value + //PayloadModel? payloadModel = null; + //instance.RootPost(payloadModel); + } + } +} diff --git a/src/src/Databox.Test/Databox.Test.csproj b/src/src/Databox.Test/Databox.Test.csproj new file mode 100644 index 0000000..11cbf75 --- /dev/null +++ b/src/src/Databox.Test/Databox.Test.csproj @@ -0,0 +1,20 @@ + + + + Databox.Test + Databox.Test + net6.0;net7.0;net8.0 + false + annotations + + + + + + + + + + + + diff --git a/src/src/Databox.Test/Model/ApiResponseTests.cs b/src/src/Databox.Test/Model/ApiResponseTests.cs new file mode 100644 index 0000000..0693ed8 --- /dev/null +++ b/src/src/Databox.Test/Model/ApiResponseTests.cs @@ -0,0 +1,75 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.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 Databox.Model; +using Databox.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Databox.Test.Model +{ + /// + /// Class for testing ApiResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ApiResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + public ApiResponseTests() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ApiResponse + /// + [Fact] + public void ApiResponseInstanceTest() + { + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); + } + + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + /// + /// Test the property 'Message' + /// + [Fact] + public void MessageTest() + { + // TODO unit test for the property 'Message' + } + } +} diff --git a/src/src/Databox.Test/Model/PayloadDataModelTests.cs b/src/src/Databox.Test/Model/PayloadDataModelTests.cs new file mode 100644 index 0000000..ac3bdaf --- /dev/null +++ b/src/src/Databox.Test/Model/PayloadDataModelTests.cs @@ -0,0 +1,111 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.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 Databox.Model; +using Databox.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Databox.Test.Model +{ + /// + /// Class for testing PayloadDataModel + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PayloadDataModelTests : IDisposable + { + // TODO uncomment below to declare an instance variable for PayloadDataModel + //private PayloadDataModel instance; + + public PayloadDataModelTests() + { + // TODO uncomment below to create an instance of PayloadDataModel + //instance = new PayloadDataModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PayloadDataModel + /// + [Fact] + public void PayloadDataModelInstanceTest() + { + // TODO uncomment below to test "IsType" PayloadDataModel + //Assert.IsType(instance); + } + + /// + /// Test the property 'MetricName' + /// + [Fact] + public void MetricNameTest() + { + // TODO unit test for the property 'MetricName' + } + + /// + /// Test the property 'DimensionName' + /// + [Fact] + public void DimensionNameTest() + { + // TODO unit test for the property 'DimensionName' + } + + /// + /// Test the property 'Unit' + /// + [Fact] + public void UnitTest() + { + // TODO unit test for the property 'Unit' + } + + /// + /// Test the property 'PeriodFrom' + /// + [Fact] + public void PeriodFromTest() + { + // TODO unit test for the property 'PeriodFrom' + } + + /// + /// Test the property 'PeriodTo' + /// + [Fact] + public void PeriodToTest() + { + // TODO unit test for the property 'PeriodTo' + } + + /// + /// Test the property 'Date' + /// + [Fact] + public void DateTest() + { + // TODO unit test for the property 'Date' + } + } +} diff --git a/src/src/Databox.Test/Model/PayloadModelTests.cs b/src/src/Databox.Test/Model/PayloadModelTests.cs new file mode 100644 index 0000000..b701de1 --- /dev/null +++ b/src/src/Databox.Test/Model/PayloadModelTests.cs @@ -0,0 +1,66 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.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 Databox.Model; +using Databox.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Databox.Test.Model +{ + /// + /// Class for testing PayloadModel + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PayloadModelTests : IDisposable + { + // TODO uncomment below to declare an instance variable for PayloadModel + //private PayloadModel instance; + + public PayloadModelTests() + { + // TODO uncomment below to create an instance of PayloadModel + //instance = new PayloadModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PayloadModel + /// + [Fact] + public void PayloadModelInstanceTest() + { + // TODO uncomment below to test "IsType" PayloadModel + //Assert.IsType(instance); + } + + /// + /// Test the property 'Data' + /// + [Fact] + public void DataTest() + { + // TODO unit test for the property 'Data' + } + } +} diff --git a/src/src/Databox/Api/DefaultApi.cs b/src/src/Databox/Api/DefaultApi.cs new file mode 100644 index 0000000..7e609cb --- /dev/null +++ b/src/src/Databox/Api/DefaultApi.cs @@ -0,0 +1,401 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using Databox.Client; +using Databox.Model; + +namespace Databox.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// + void RootPost(PayloadModel? payloadModel = default(PayloadModel?)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// ApiResponse of Object(void) + ApiResponse RootPostWithHttpInfo(PayloadModel? payloadModel = default(PayloadModel?)); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task RootPostAsync(PayloadModel? payloadModel = default(PayloadModel?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> RootPostWithHttpInfoAsync(PayloadModel? payloadModel = default(PayloadModel?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApi : IDefaultApiSync, IDefaultApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IDisposable, IDefaultApi + { + private Databox.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// + public DefaultApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// The target service's base path in URL format. + /// + /// + public DefaultApi(string basePath) + { + this.Configuration = Databox.Client.Configuration.MergeConfigurations( + Databox.Client.GlobalConfiguration.Instance, + new Databox.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new Databox.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + this.AsynchronousClient = this.ApiClient; + this.ExceptionFactory = Databox.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// An instance of Configuration. + /// + /// + public DefaultApi(Databox.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Databox.Client.Configuration.MergeConfigurations( + Databox.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new Databox.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + this.AsynchronousClient = this.ApiClient; + ExceptionFactory = Databox.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public DefaultApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public DefaultApi(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = Databox.Client.Configuration.MergeConfigurations( + Databox.Client.GlobalConfiguration.Instance, + new Databox.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new Databox.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + this.AsynchronousClient = this.ApiClient; + this.ExceptionFactory = Databox.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// + /// An instance of HttpClient. + /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public DefaultApi(HttpClient client, Databox.Client.Configuration configuration, HttpClientHandler handler = null) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = Databox.Client.Configuration.MergeConfigurations( + Databox.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new Databox.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + this.AsynchronousClient = this.ApiClient; + ExceptionFactory = Databox.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + /// + public DefaultApi(Databox.Client.ISynchronousClient client, Databox.Client.IAsynchronousClient asyncClient, Databox.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Databox.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + this.ApiClient?.Dispose(); + } + + /// + /// Holds the ApiClient if created + /// + public Databox.Client.ApiClient ApiClient { get; set; } = null; + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Databox.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Databox.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Databox.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Databox.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// + public void RootPost(PayloadModel? payloadModel = default(PayloadModel?)) + { + RootPostWithHttpInfo(payloadModel); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// ApiResponse of Object(void) + public Databox.Client.ApiResponse RootPostWithHttpInfo(PayloadModel? payloadModel = default(PayloadModel?)) + { + Databox.Client.RequestOptions localVarRequestOptions = new Databox.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Databox.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Databox.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = payloadModel; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("RootPost", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task RootPostAsync(PayloadModel? payloadModel = default(PayloadModel?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await RootPostWithHttpInfoAsync(payloadModel, cancellationToken).ConfigureAwait(false); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> RootPostWithHttpInfoAsync(PayloadModel? payloadModel = default(PayloadModel?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Databox.Client.RequestOptions localVarRequestOptions = new Databox.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + + var localVarContentType = Databox.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Databox.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = payloadModel; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("RootPost", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/src/src/Databox/Client/ApiClient.cs b/src/src/Databox/Client/ApiClient.cs new file mode 100644 index 0000000..1c00801 --- /dev/null +++ b/src/src/Databox/Client/ApiClient.cs @@ -0,0 +1,788 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using System.Net.Http; +using System.Net.Http.Headers; +using Polly; + +namespace Databox.Client +{ + /// + /// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is Databox.Model.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((Databox.Model.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public async Task Deserialize(HttpResponseMessage response) + { + var result = (T) await Deserialize(response, typeof(T)).ConfigureAwait(false); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal async Task Deserialize(HttpResponseMessage response, Type type) + { + IList headers = new List(); + // process response headers, e.g. Access-Control-Allow-Methods + foreach (var responseHeader in response.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // process response content headers, e.g. Content-Type + foreach (var responseHeader in response.Content.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // RFC 2183 & RFC 2616 + var fileNameRegex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$", RegexOptions.IgnoreCase); + if (type == typeof(byte[])) // return byte array + { + return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + } + else if (type == typeof(FileParameter)) + { + if (headers != null) { + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + return new FileParameter(fileName, await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + } + } + return new FileParameter(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + if (headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false), null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + /// + /// The Dispose method will manage the HttpClient lifecycle when not passed by constructor. + /// + public partial class ApiClient : IDisposable, ISynchronousClient, IAsynchronousClient + { + private readonly string _baseUrl; + + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + public ApiClient() : + this(Databox.Client.GlobalConfiguration.Instance.BasePath) + { + } + + /// + /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); + _disposeClient = true; + _baseUrl = basePath; + } + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, Databox.Client.GlobalConfiguration.Instance.BasePath, handler) + { + } + + /// + /// Initializes a new instance of the . + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + if(_disposeClient) { + _httpClient.Dispose(); + } + } + + /// Prepares multipart/form-data content + HttpContent PrepareMultipartFormDataContent(RequestOptions options) + { + string boundary = "---------" + Guid.NewGuid().ToString().ToUpperInvariant(); + var multipartContent = new MultipartFormDataContent(boundary); + foreach (var formParameter in options.FormParameters) + { + multipartContent.Add(new StringContent(formParameter.Value), formParameter.Key); + } + + if (options.FileParameters != null && options.FileParameters.Count > 0) + { + foreach (var fileParam in options.FileParameters) + { + foreach (var file in fileParam.Value) + { + var content = new StreamContent(file.Content); + content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType); + multipartContent.Add(content, fileParam.Key, file.Name); + } + } + } + return multipartContent; + } + + /// + /// Provides all logic for constructing a new HttpRequestMessage. + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the a HttpRequestMessage. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new HttpRequestMessage instance. + /// + private HttpRequestMessage NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path); + + builder.AddPathParameters(options.PathParameters); + + builder.AddQueryParameters(options.QueryParameters); + + HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); + + if (configuration.UserAgent != null) + { + request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent); + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.Headers.Add(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + // Todo make content headers actually content headers + request.Headers.TryAddWithoutValidation(headerParam.Key, value); + } + } + } + + List> contentList = new List>(); + + string contentType = null; + if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type")) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes.FirstOrDefault(); + } + + if (contentType == "multipart/form-data") + { + request.Content = PrepareMultipartFormDataContent(options); + } + else if (contentType == "application/x-www-form-urlencoded") + { + request.Content = new FormUrlEncodedContent(options.FormParameters); + } + else + { + if (options.Data != null) + { + if (options.Data is FileParameter fp) + { + contentType = contentType ?? "application/octet-stream"; + + var streamContent = new StreamContent(fp.Content); + streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + request.Content = streamContent; + } + else + { + var serializer = new CustomJsonCodec(SerializerSettings, configuration); + request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(), + "application/json"); + } + } + } + + + + // TODO provide an alternative that allows cookies per request instead of per API client + if (options.Cookies != null && options.Cookies.Count > 0) + { + request.Properties["CookieContainer"] = options.Cookies; + } + + return request; + } + + partial void InterceptRequest(HttpRequestMessage req); + partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); + + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + { + T result = (T) responseData; + string rawContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + + var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) + { + ErrorText = response.ReasonPhrase, + Cookies = new List() + }; + + // process response headers, e.g. Access-Control-Allow-Methods + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + // process response content headers, e.g. Content-Type + if (response.Content.Headers != null) + { + foreach (var responseHeader in response.Content.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (_httpClientHandler != null && response != null) + { + try { + foreach (Cookie cookie in _httpClientHandler.CookieContainer.GetCookies(uri)) + { + transformed.Cookies.Add(cookie); + } + } + catch (PlatformNotSupportedException) {} + } + + return transformed; + } + + private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) + { + return ExecAsync(req, configuration).GetAwaiter().GetResult(); + } + + private async Task> ExecAsync(HttpRequestMessage req, + IReadableConfiguration configuration, + System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + CancellationTokenSource timeoutTokenSource = null; + CancellationTokenSource finalTokenSource = null; + var deserializer = new CustomJsonCodec(SerializerSettings, configuration); + var finalToken = cancellationToken; + + try + { + if (configuration.Timeout > 0) + { + timeoutTokenSource = new CancellationTokenSource(configuration.Timeout); + finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token); + finalToken = finalTokenSource.Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { + response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false); + } + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri).ConfigureAwait(false); + } + + object responseData = await deserializer.Deserialize(response).ConfigureAwait(false); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Databox.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri).ConfigureAwait(false); + } + catch (OperationCanceledException original) + { + if (timeoutTokenSource != null && timeoutTokenSource.IsCancellationRequested) + { + throw new TaskCanceledException($"[{req.Method}] {req.RequestUri} was timeout.", + new TimeoutException(original.Message, original)); + } + throw; + } + finally + { + if (timeoutTokenSource != null) + { + timeoutTokenSource.Dispose(); + } + + if (finalTokenSource != null) + { + finalTokenSource.Dispose(); + } + } + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(new HttpMethod("PATCH"), path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(new HttpMethod("PATCH"), path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/src/src/Databox/Client/ApiException.cs b/src/src/Databox/Client/ApiException.cs new file mode 100644 index 0000000..5e5c5c0 --- /dev/null +++ b/src/src/Databox/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Databox.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/src/src/Databox/Client/ApiResponse.cs b/src/src/Databox/Client/ApiResponse.cs new file mode 100644 index 0000000..07a07ea --- /dev/null +++ b/src/src/Databox/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Databox.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/src/src/Databox/Client/ClientUtils.cs b/src/src/Databox/Client/ClientUtils.cs new file mode 100644 index 0000000..999ca05 --- /dev/null +++ b/src/src/Databox/Client/ClientUtils.cs @@ -0,0 +1,247 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; + +namespace Databox.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// 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). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) { + List entries = new List(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry, configuration)); + return string.Join(",", entries); + } + if (obj is Enum && HasEnumMemberAttrValue(obj)) + return GetEnumMemberAttrValue(obj); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Is the Enum decorated with EnumMember Attribute + /// + /// + /// true if found + private static bool HasEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) return true; + return false; + } + + /// + /// Get the EnumMember value + /// + /// + /// EnumMember value as string otherwise null + private static string GetEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) + { + return attr.Value; + } + return null; + } + } +} diff --git a/src/src/Databox/Client/Configuration.cs b/src/src/Databox/Client/Configuration.cs new file mode 100644 index 0000000..9ebda38 --- /dev/null +++ b/src/src/Databox/Client/Configuration.cs @@ -0,0 +1,612 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Net.Http; +using System.Net.Security; + +namespace Databox.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "0.0.2"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + private bool _useDefaultCredentials = false; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for accessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + + /// + /// Gets or sets the operation servers defined in the OpenAPI spec. + /// + /// The operation servers + private IReadOnlyDictionary>> _operationServers; + + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/0.0.2/csharp"); + BasePath = "http://localhost:8080/q/openapi"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", "http://localhost:8080/q/openapi"}, + {"description", "Dev mode server description"}, + } + } + }; + OperationServers = new Dictionary>>() + { + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://localhost:8080/q/openapi") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath + { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + public virtual bool UseDefaultCredentials + { + get { return _useDefaultCredentials; } + set { _useDefaultCredentials = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Gets or sets the operation servers. + /// + /// The operation servers. + public virtual IReadOnlyDictionary>> OperationServers + { + get { return _operationServers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Operation servers may not be null."); + } + _operationServers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(Servers, index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + return GetServerUrl(Servers, index, inputVariables); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index) + { + return GetOperationServerUrl(operation, index, null); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index, Dictionary inputVariables) + { + if (operation != null && OperationServers.TryGetValue(operation, out var operationServer)) + { + return GetServerUrl(operationServer, index, inputVariables); + } + + return null; + } + + /// + /// Returns URL based on server settings. + /// + /// Dictionary of server settings. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + private string GetServerUrl(IList> servers, int index, Dictionary inputVariables) + { + if (index < 0 || index >= servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = servers[index]; + string url = (string)server["url"]; + + if (server.ContainsKey("variables")) + { + // go through each variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use default value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + } + + return url; + } + + /// + /// Gets and Sets the RemoteCertificateValidationCallback + /// + public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK (Databox) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0\n"; + report += " SDK Package Version: 0.0.2\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, + ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, + UseDefaultCredentials = second.UseDefaultCredentials, + RemoteCertificateValidationCallback = second.RemoteCertificateValidationCallback ?? first.RemoteCertificateValidationCallback, + }; + return config; + } + #endregion Static Members + } +} diff --git a/src/src/Databox/Client/ExceptionFactory.cs b/src/src/Databox/Client/ExceptionFactory.cs new file mode 100644 index 0000000..51d8f21 --- /dev/null +++ b/src/src/Databox/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Databox.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/src/src/Databox/Client/FileParameter.cs b/src/src/Databox/Client/FileParameter.cs new file mode 100644 index 0000000..a2b6b62 --- /dev/null +++ b/src/src/Databox/Client/FileParameter.cs @@ -0,0 +1,80 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.IO; + +namespace Databox.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content type of the file + /// + public string ContentType { get; set; } = "application/octet-stream"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The content type of the file + /// The file content + public FileParameter(string filename, string contentType, Stream content) + { + Name = filename; + ContentType = contentType; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/src/src/Databox/Client/GlobalConfiguration.cs b/src/src/Databox/Client/GlobalConfiguration.cs new file mode 100644 index 0000000..04464d2 --- /dev/null +++ b/src/src/Databox/Client/GlobalConfiguration.cs @@ -0,0 +1,67 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.Collections.Generic; + +namespace Databox.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} diff --git a/src/src/Databox/Client/IApiAccessor.cs b/src/src/Databox/Client/IApiAccessor.cs new file mode 100644 index 0000000..74ab2af --- /dev/null +++ b/src/src/Databox/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Databox.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/src/src/Databox/Client/IAsynchronousClient.cs b/src/src/Databox/Client/IAsynchronousClient.cs new file mode 100644 index 0000000..bc69fd9 --- /dev/null +++ b/src/src/Databox/Client/IAsynchronousClient.cs @@ -0,0 +1,100 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; + +namespace Databox.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/src/src/Databox/Client/IReadableConfiguration.cs b/src/src/Databox/Client/IReadableConfiguration.cs new file mode 100644 index 0000000..e1d3190 --- /dev/null +++ b/src/src/Databox/Client/IReadableConfiguration.cs @@ -0,0 +1,141 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; + +namespace Databox.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time format. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + bool UseDefaultCredentials { get; } + + /// + /// Get the servers associated with the operation. + /// + /// Operation servers. + IReadOnlyDictionary>> OperationServers { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets the Operation server url at the provided index. + /// + /// Operation server name. + /// Index of the operation server settings. + /// + string GetOperationServerUrl(string operation, int index); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + + /// + /// Callback function for handling the validation of remote certificates. Useful for certificate pinning and + /// overriding certificate errors in the scope of a request. + /// + RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; } + } +} diff --git a/src/src/Databox/Client/ISynchronousClient.cs b/src/src/Databox/Client/ISynchronousClient.cs new file mode 100644 index 0000000..d647d91 --- /dev/null +++ b/src/src/Databox/Client/ISynchronousClient.cs @@ -0,0 +1,93 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.IO; + +namespace Databox.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/src/src/Databox/Client/Multimap.cs b/src/src/Databox/Client/Multimap.cs new file mode 100644 index 0000000..81aeded --- /dev/null +++ b/src/src/Databox/Client/Multimap.cs @@ -0,0 +1,295 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Databox.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/src/src/Databox/Client/OpenAPIDateConverter.cs b/src/src/Databox/Client/OpenAPIDateConverter.cs new file mode 100644 index 0000000..7a30336 --- /dev/null +++ b/src/src/Databox/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Databox.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 OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/src/src/Databox/Client/RequestOptions.cs b/src/src/Databox/Client/RequestOptions.cs new file mode 100644 index 0000000..2c6202d --- /dev/null +++ b/src/src/Databox/Client/RequestOptions.cs @@ -0,0 +1,74 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace Databox.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Multimap FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Multimap(); + Cookies = new List(); + } + } +} diff --git a/src/src/Databox/Client/RetryConfiguration.cs b/src/src/Databox/Client/RetryConfiguration.cs new file mode 100644 index 0000000..998d91c --- /dev/null +++ b/src/src/Databox/Client/RetryConfiguration.cs @@ -0,0 +1,31 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Polly; +using System.Net.Http; + +namespace Databox.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public static class RetryConfiguration + { + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } + } +} diff --git a/src/src/Databox/Client/WebRequestPathBuilder.cs b/src/src/Databox/Client/WebRequestPathBuilder.cs new file mode 100644 index 0000000..51e4d35 --- /dev/null +++ b/src/src/Databox/Client/WebRequestPathBuilder.cs @@ -0,0 +1,53 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; + +namespace Databox.Client +{ + /// + /// A URI builder + /// + class WebRequestPathBuilder + { + private string _baseUrl; + private string _path; + private string _query = "?"; + public WebRequestPathBuilder(string baseUrl, string path) + { + _baseUrl = baseUrl; + _path = path; + } + + public void AddPathParameters(Dictionary parameters) + { + foreach (var parameter in parameters) + { + _path = _path.Replace("{" + parameter.Key + "}", Uri.EscapeDataString(parameter.Value)); + } + } + + public void AddQueryParameters(Multimap parameters) + { + foreach (var parameter in parameters) + { + foreach (var value in parameter.Value) + { + _query = _query + parameter.Key + "=" + Uri.EscapeDataString(value) + "&"; + } + } + } + + public string GetFullUri() + { + return _baseUrl + _path + _query.Substring(0, _query.Length - 1); + } + } +} diff --git a/src/src/Databox/Databox.csproj b/src/src/Databox/Databox.csproj new file mode 100644 index 0000000..7b0d637 --- /dev/null +++ b/src/src/Databox/Databox.csproj @@ -0,0 +1,35 @@ + + + + false + net6.0;net7.0;net8.0 + Databox + Databox + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Databox + 0.0.2 + bin\$(Configuration)\$(TargetFramework)\Databox.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + annotations + + + + + + + + + + + + + + + diff --git a/src/src/Databox/Model/AbstractOpenAPISchema.cs b/src/src/Databox/Model/AbstractOpenAPISchema.cs new file mode 100644 index 0000000..b9e1edf --- /dev/null +++ b/src/src/Databox/Model/AbstractOpenAPISchema.cs @@ -0,0 +1,76 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Databox.Model +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + public abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/src/src/Databox/Model/ApiResponse.cs b/src/src/Databox/Model/ApiResponse.cs new file mode 100644 index 0000000..1850509 --- /dev/null +++ b/src/src/Databox/Model/ApiResponse.cs @@ -0,0 +1,92 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using FileParameter = Databox.Client.FileParameter; +using OpenAPIDateConverter = Databox.Client.OpenAPIDateConverter; + +namespace Databox.Model +{ + /// + /// ApiResponse + /// + [DataContract(Name = "ApiResponse")] + public partial class ApiResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// status. + /// message. + public ApiResponse(string status = default(string), string message = default(string)) + { + this.Status = status; + this.Message = message; + } + + /// + /// Gets or Sets Status + /// + [DataMember(Name = "status", EmitDefaultValue = false)] + public string Status { get; set; } + + /// + /// Gets or Sets Message + /// + [DataMember(Name = "message", EmitDefaultValue = false)] + public string Message { 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 ApiResponse {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/src/src/Databox/Model/PayloadDataModel.cs b/src/src/Databox/Model/PayloadDataModel.cs new file mode 100644 index 0000000..fbce727 --- /dev/null +++ b/src/src/Databox/Model/PayloadDataModel.cs @@ -0,0 +1,143 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using FileParameter = Databox.Client.FileParameter; +using OpenAPIDateConverter = Databox.Client.OpenAPIDateConverter; + +namespace Databox.Model +{ + /// + /// PayloadDataModel + /// + [DataContract(Name = "PayloadDataModel")] + public partial class PayloadDataModel : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected PayloadDataModel() { } + /// + /// Initializes a new instance of the class. + /// + /// example metric name would be '$sales'. + /// example dimension would be 'channel'. + /// unit. + /// required if date not provided. + /// required if date not provided. + /// required periods not provided (required). + public PayloadDataModel(decimal metricName = default(decimal), string dimensionName = default(string), string unit = default(string), string periodFrom = default(string), string periodTo = default(string), string date = default(string)) + { + // to ensure "date" is required (not null) + if (date == null) + { + throw new ArgumentNullException("date is a required property for PayloadDataModel and cannot be null"); + } + this.Date = date; + this.MetricName = metricName; + this.DimensionName = dimensionName; + this.Unit = unit; + this.PeriodFrom = periodFrom; + this.PeriodTo = periodTo; + } + + /// + /// example metric name would be '$sales' + /// + /// example metric name would be '$sales' + [DataMember(Name = "$<metric_name>", EmitDefaultValue = false)] + public decimal MetricName { get; set; } + + /// + /// example dimension would be 'channel' + /// + /// example dimension would be 'channel' + [DataMember(Name = "<dimension_name>", EmitDefaultValue = false)] + public string DimensionName { get; set; } + + /// + /// Gets or Sets Unit + /// + [DataMember(Name = "unit", EmitDefaultValue = false)] + public string Unit { get; set; } + + /// + /// required if date not provided + /// + /// required if date not provided + [DataMember(Name = "periodFrom", EmitDefaultValue = false)] + public string PeriodFrom { get; set; } + + /// + /// required if date not provided + /// + /// required if date not provided + [DataMember(Name = "periodTo", EmitDefaultValue = false)] + public string PeriodTo { get; set; } + + /// + /// required periods not provided + /// + /// required periods not provided + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] + public string Date { 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 PayloadDataModel {\n"); + sb.Append(" MetricName: ").Append(MetricName).Append("\n"); + sb.Append(" DimensionName: ").Append(DimensionName).Append("\n"); + sb.Append(" Unit: ").Append(Unit).Append("\n"); + sb.Append(" PeriodFrom: ").Append(PeriodFrom).Append("\n"); + sb.Append(" PeriodTo: ").Append(PeriodTo).Append("\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/src/src/Databox/Model/PayloadModel.cs b/src/src/Databox/Model/PayloadModel.cs new file mode 100644 index 0000000..bffd426 --- /dev/null +++ b/src/src/Databox/Model/PayloadModel.cs @@ -0,0 +1,83 @@ +/* + * Static OpenAPI document of Push API resource + * + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 1.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using FileParameter = Databox.Client.FileParameter; +using OpenAPIDateConverter = Databox.Client.OpenAPIDateConverter; + +namespace Databox.Model +{ + /// + /// PayloadModel + /// + [DataContract(Name = "PayloadModel")] + public partial class PayloadModel : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data. + public PayloadModel(List data = default(List)) + { + this.Data = data; + } + + /// + /// Gets or Sets Data + /// + [DataMember(Name = "data", EmitDefaultValue = false)] + public List Data { 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 PayloadModel {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/src/test/test1 b/src/test/test1 deleted file mode 100644 index e69de29..0000000 diff --git a/src/test2/test2 b/src/test2/test2 deleted file mode 100644 index e69de29..0000000