diff --git a/.gitignore b/.gitignore index 6e435e8592d..16bc70cd3cb 100644 --- a/.gitignore +++ b/.gitignore @@ -148,6 +148,9 @@ samples/client/petstore/csharp/SwaggerClient/bin/Debug/ samples/client/petstore/csharp/SwaggerClient/packages samples/client/petstore/csharp/SwaggerClient/TestResult.xml samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.userprefs +samples/client/petstore/csharp-dotnet-core/obj/* +samples/client/petstore/csharp-dotnet-core/bin/* +samples/client/petstore/csharp-dotnet-core/.vs/* # Python *.pyc diff --git a/bin/csharp-dotnet-core-petstore.sh b/bin/csharp-dotnet-core-petstore.sh new file mode 100644 index 00000000000..52a9aa4374a --- /dev/null +++ b/bin/csharp-dotnet-core-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l csharp-dotnet-core -o samples/client/petstore/csharp-dotnet-core/SwaggerClientTest/Lib/SwaggerClient --additional-properties hideGenerationTimestamp=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/csharp-dotnet-core-petstore.bat b/bin/windows/csharp-dotnet-core-petstore.bat new file mode 100644 index 00000000000..8987d3f5114 --- /dev/null +++ b/bin/windows/csharp-dotnet-core-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l csharp-dotnet-core -o samples/client/petstore/csharp-dotnet-core/SwaggerClientTest/Lib/SwaggerClient --additional-properties hideGenerationTimestamp=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 1d15ac4fb1a..ac3a939e832 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -324,6 +324,7 @@ private void addMustacheLambdas(Map objs) { .put("lowercase", new LowercaseLambda().generator(this)) .put("uppercase", new UppercaseLambda()) .put("titlecase", new TitlecaseLambda()) + .put("pascalcase", new PascalCaseLambda()) .put("camelcase", new CamelCaseLambda().generator(this)) .put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true)) .put("indented", new IndentedLambda()) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotnetCoreClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotnetCoreClientCodegen.java new file mode 100644 index 00000000000..1ffa5f32ec0 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotnetCoreClientCodegen.java @@ -0,0 +1,201 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import org.checkerframework.common.returnsreceiver.qual.This; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +public class CsharpDotnetCoreClientCodegen extends AbstractCSharpCodegen { + public static final String CLIENT_PACKAGE = "clientPackage"; + public static final String USE_CSPROJ_FILE = "useCsProjFile"; + public static final String DefaultargetFramwork = "net8.0"; + protected String clientPackage = "IO.Swagger.Client"; + protected String systemTextJsonVersion = "8.0.3"; + protected String apiDocPath = "docs"; + protected String modelDocPath = "docs"; + + protected Map versions = new HashMap<>(); + protected String exceptionTypeName; + protected String apiClientBaseTypeName; + + public CsharpDotnetCoreClientCodegen() { + super(); + + versions.put("net8.0","8.0.3"); + versions.put("net7.0","7.0.4"); + versions.put("net6.0","6.0.9"); + versions.put("net5.0","5.0.2"); + + importMapping.clear(); + + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + + setApiPackage(packageName + ".Api"); + setModelPackage(packageName + ".Model"); + setClientPackage(packageName + ".Client"); + setSourceFolder("src" + File.separator + "main" + File.separator + "CsharpDotNet2"); + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "C# package name (convention: Camel.Case).") + .defaultValue(packageName)); + cliOptions.add(new CliOption(CodegenConstants.DOTNET_FRAMEWORK, + CodegenConstants.DOTNET_FRAMEWORK_DESC) + .defaultValue("net8.0")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, + "C# package version.") + .defaultValue(packageVersion)); + } + + @Override + public void processOpts() { + super.processOpts(); + + sourceFolder = ""; + + if (additionalProperties.containsKey(CLIENT_PACKAGE)) { + setClientPackage((String) additionalProperties.get(CLIENT_PACKAGE)); + } else { + additionalProperties.put(CLIENT_PACKAGE, getClientPackage()); + } + + String generatorVersion = this.getClass().getPackage().getSpecificationVersion(); + if(generatorVersion == null) { + generatorVersion = "1.0"; + } + additionalProperties.put("generateorVersion", generatorVersion); + + final String clientPackage = getClientPackage(); + + if(!additionalProperties.containsKey("apiDocPath")) { + additionalProperties.put("apiDocPath", apiDocPath); + } + if(!additionalProperties.containsKey("modelDocPath")) { + additionalProperties.put("modelDocPath", modelDocPath); + } + + String exceptionTypeName = clientPackage.replace(".", "") + "ApiException"; + additionalProperties.put("exceptionTypeName", exceptionTypeName); + String apiClientBaseTypeName = clientPackage.replace(".", "") + "ApiClientBase"; + additionalProperties.put("apiClientBaseTypeName", apiClientBaseTypeName); + + supportingFiles.add(new SupportingFile("ApiException.mustache", "", exceptionTypeName + ".cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", "", "ApiClient.cs")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + if (additionalProperties.containsKey(USE_CSPROJ_FILE) && Boolean.parseBoolean(additionalProperties.get(USE_CSPROJ_FILE).toString())) { + supportingFiles.add(new SupportingFile("csproj.mustache", "", clientPackage + ".csproj")); + } + if(!additionalProperties.containsKey(CodegenConstants.DOTNET_FRAMEWORK)) { + additionalProperties.put(CodegenConstants.DOTNET_FRAMEWORK, DefaultargetFramwork); + } + String version = additionalProperties.get(CodegenConstants.DOTNET_FRAMEWORK).toString(); + boolean contains = versions.containsKey(version); + if(contains) { + setSystemTextJsonVersion(versions.get(version)); + } + } + + @Override + public String apiPackage() { + return packageName + ".Clients"; + } + + @Override + public String modelPackage() { + return packageName + ".Models"; + } + + public void setSystemTextJsonVersion(String systemTextJsonVersion){ + this.systemTextJsonVersion = systemTextJsonVersion; + } + + public String getSystemTextJsonVersion(){ + return this.systemTextJsonVersion; + } + + public String getClientPackage() { + return clientPackage; + } + + public void setClientPackage(String clientPackage) { + this.clientPackage = clientPackage; + } + + @Override + protected void processOperation(CodegenOperation operation) { + CodegenParameter cancellationTokenParameter = new CodegenParameter(); + cancellationTokenParameter.dataType = "CancellationToken"; + cancellationTokenParameter.paramName = "ct"; + cancellationTokenParameter.secondaryParam = true; + operation.hasMore = false; + + if(operation.allParams.size() != 0) { + CodegenParameter lastParameter = operation.allParams.get(operation.allParams.size() - 1); + lastParameter.hasMore = true; + } + + operation.allParams.add(cancellationTokenParameter); + + super.processOperation(operation); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "csharp-dotnet-core"; + } + + @Override + public String getHelp() { + return "Generates a C# dotnet Core client library."; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + "Clients"; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + "Models"; + } + + @Override + public String apiDocFileFolder() { + return handleAbsolutePathIfPresentFromProperties("apiDocPath"); + } + + @Override + public String modelDocFileFolder() { + return handleAbsolutePathIfPresentFromProperties("modelDocPath"); + } + + private String handleAbsolutePathIfPresentFromProperties(String propertyWithPathName){ + String pathFromProperty = additionalProperties.get(propertyWithPathName).toString(); + return handleAbsolutePathIfPresent(pathFromProperty); + } + + private String handleAbsolutePathIfPresent(String value){ + String pathFromProperties = value; + Path path = Paths.get(pathFromProperties); + + if (path.isAbsolute()) { + return pathFromProperties.replace('/', File.separatorChar); + } + + return (outputFolder + "/" +pathFromProperties).replace('/', File.separatorChar); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/mustache/PascalCaseLambda.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/mustache/PascalCaseLambda.java new file mode 100644 index 00000000000..d1b036aad22 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/mustache/PascalCaseLambda.java @@ -0,0 +1,60 @@ +package io.swagger.codegen.mustache; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.DefaultCodegen; + +import java.io.IOException; +import java.io.Writer; + +/** + * Converts text in a fragment to PascalCase. + * + * Register: + *
+ * additionalProperties.put("pascalcase", new PascalCaseLambda());
+ * 
+ * + * Use: + *
+ * {{#pascalcase}}{{name}}{{/pascalcase}}
+ * 
+ */ +public class PascalCaseLambda implements Mustache.Lambda { + private CodegenConfig generator = null; + private Boolean escapeParam = false; + + public PascalCaseLambda() { + + } + + public PascalCaseLambda generator(final CodegenConfig generator) { + this.generator = generator; + return this; + } + + public PascalCaseLambda escapeAsParamName(final Boolean escape) { + this.escapeParam = escape; + return this; + } + + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + String text = DefaultCodegen.camelize(fragment.execute(), false); + if (generator != null) { + text = generator.sanitizeName(text); + if (generator.reservedWords().contains(text)) { + // Escaping must be done *after* camelize, because generators may escape using characters removed by camelize function. + text = generator.escapeReservedWord(text); + } + + if (escapeParam) { + // NOTE: many generators call escapeReservedWord in toParamName, but we can't assume that's always the case. + // Here, we'll have to accept that we may be duplicating some work. + text = generator.toParamName(text); + } + } + writer.write(text); + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 14f7499ba81..626847cd1b4 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -11,6 +11,7 @@ io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.ConfluenceWikiGenerator io.swagger.codegen.languages.CppRestClientCodegen io.swagger.codegen.languages.CsharpDotNet2ClientCodegen +io.swagger.codegen.languages.CsharpDotnetCoreClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.DartJaguarClientCodegen io.swagger.codegen.languages.ElixirClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiClient.mustache new file mode 100644 index 00000000000..442ddf2ee3c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiClient.mustache @@ -0,0 +1,405 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Reflection; +using System.Globalization; +using System.Text; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace {{clientPackage}}; + +/// +/// Base type for API client is mainly responsible for making the HTTP call to the API. +/// +[GeneratedCode("swagger-codegen", "{{generateorVersion}}")] +public abstract class {{apiClientBaseTypeName}} +{ + protected readonly HttpClient _httpClient; + protected readonly string _basePath; + protected readonly JsonSerializerOptions _options; + + /// + /// Initializes a new instance of the class. + /// + /// Client for making http calls. + /// The base path. + /// Serialization settings. + protected {{apiClientBaseTypeName}}(HttpClient httpClient, string basePath, JsonSerializerOptions options = null) + { + _httpClient = httpClient; + _basePath = basePath; + _options = options ?? JsonSerializerOptions.Default; + } + + protected virtual string ContentType => "application/json-patch+json"; + protected virtual string Accept => "application/json"; + protected virtual IFormatProvider DateTimeFormatForQuery => CultureInfo.CurrentCulture.DateTimeFormat; + + /// + /// Makes the HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// Object to be serialized for http request body. + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Operation cancellation token. + /// Result of request. + protected virtual async Task CallApi( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + CancellationToken ct + ) + { + using (var request = new HttpRequestMessage()) + { + PrepareRequest(path, method, queryParams, body, headerParams, formParams, fileParams, request); + HttpResponseMessage response = null; + try + { + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + + var headers = CollectHeaders(response); + + var status = (int)response.StatusCode; + if (status is >= 200 and < 300) + { + return await ReadObjectResponseAsync(response, headers, ct).ConfigureAwait(false); + } + else + { + var responseData = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + throw new {{exceptionTypeName}}(status, "The HTTP status code of the response was not expected (" + status + ").", responseData, headers, null); + } + } + finally + { + response?.Dispose(); + } + } + } + + /// + /// Makes the HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// Object to be serialized for http request body. + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Operation cancellation token. + /// Result of request. + protected virtual async Task CallApi( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + CancellationToken ct + ) + { + using (var request = new HttpRequestMessage()) + { + PrepareRequest(path, method, queryParams, body, headerParams, formParams, fileParams, request); + + HttpResponseMessage response = null; + try + { + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + + var headers = CollectHeaders(response); + + var status = (int)response.StatusCode; + if (status is < 200 or >= 300) + { + var responseData = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + throw new {{exceptionTypeName}}(status, "The HTTP status code of the response was not expected (" + status + ").", responseData, headers, null); + } + } + finally + { + response?.Dispose(); + } + } + } + + private void PrepareRequest( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + HttpRequestMessage request + ) + { + request.Method = method; + + // prepare request body + if (body != null) + { + string json; + if (body is string stringBody) + { + json = stringBody; + } + else + { + json = JsonSerializer.Serialize(body, _options); + } + + var content = new StringContent(json); + content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType); + request.Content = content; + } + + //form-data + if (formParams != null && formParams.Count > 0) + { + request.Content = new FormUrlEncodedContent(formParams); + } + + // file sending + if(fileParams != null) + { + using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) + { + foreach(var kvp in fileParams) + { + content.Add(ToStreamContent(kvp.Value)); + } + request.Content = content; + } + } + + // headers + request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(Accept)); + if (headerParams != null) + { + foreach (var kvp in headerParams) + { + request.Headers.Add(kvp.Key, kvp.Value); + } + } + + // build url + var urlBuilder = new StringBuilder(); + if (!string.IsNullOrEmpty(_basePath)) + { + urlBuilder.Append(_basePath); + } + + urlBuilder.Append(path); + + urlBuilder.Append('?'); + if (queryParams != null) + { + foreach (var kvp in queryParams) + { + urlBuilder.Append( + Uri.EscapeDataString(kvp.Key) + ).Append('=') + .Append( + Uri.EscapeDataString( + ConvertToString(kvp.Value, CultureInfo.InvariantCulture) + ) + ).Append('&'); + } + + urlBuilder.Length--; + } + + var url = urlBuilder.ToString(); + request.RequestUri = new Uri(url, UriKind.RelativeOrAbsolute); + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async Task ReadObjectResponseAsync( + HttpResponseMessage response, + IReadOnlyDictionary> headers, + CancellationToken ct + ) + { + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + try + { + return JsonSerializer.Deserialize(responseText, _options); + } + catch (JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new {{exceptionTypeName}}((int)response.StatusCode, message, responseText, headers, exception); + } + } + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false)) + { + return await JsonSerializer.DeserializeAsync(responseStream, _options, ct); + } + } + catch (JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new {{exceptionTypeName}}((int)response.StatusCode, message, string.Empty, headers, exception); + } + } + + private string ConvertToString(object value, IFormatProvider cultureInfo) + { + if (value == null) + { + return String.Empty; + } + + if (value is Enum) + { + var name = Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = value.GetType().GetTypeInfo().GetDeclaredField(name); + if (field != null) + { + var attribute = field.GetCustomAttribute(typeof(System.Runtime.Serialization.EnumMemberAttribute)) as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value ?? name; + } + } + + var converted = Convert.ToString(Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted ?? string.Empty; + } + } + else if (value is bool asBool) + { + return Convert.ToString(asBool, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[] asByte) + { + return Convert.ToBase64String(asByte); + } + else if (value is string[] stringArray) + { + return string.Join(",", stringArray); + } + else if (value.GetType().IsArray) + { + var valueArray = (Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); + } + + var result = Convert.ToString(value, cultureInfo); + return result ?? String.Empty; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list of string, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + protected virtual string ParameterToString(object obj) + { + 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(DateTimeFormatForQuery); + if (obj is List list) + return String.Join(",", list.ToArray()); + return Convert.ToString(obj); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public static FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream fs) + { + return new FileParameter(name, stream, Path.GetFileName(fs.Name)); + } + return new FileParameter(name, stream, "no_file_name_provided"); + } + + private static Dictionary> CollectHeaders(HttpResponseMessage response) + { + var headers = new Dictionary>(response.Headers.Count() + response.Content.Headers.Count()); + foreach (var item in response.Headers) + { + headers[item.Key] = item.Value; + } + + foreach (var item in response.Content.Headers) + { + headers[item.Key] = item.Value; + } + + return headers; + } + + private StreamContent ToStreamContent(FileParameter fileParameter) + { + var stream = fileParameter.FileData; + var streamContent = new StreamContent(stream); + + streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(fileParameter.ContentType); + + var dispositionHeader = ContentDispositionHeaderValue.Parse($"form-data; name=\"{fileParameter.ParameterName}\"; filename=\"{fileParameter.FileName}\""); + streamContent.Headers.ContentDisposition = dispositionHeader; + + return streamContent; + } +} + +public class FileParameter +{ + public FileParameter(string parameterName, Stream fileData, string fileName, string contentType = null) + { + ParameterName = parameterName; + FileName = fileName; + FileData = fileData; + ContentType = contentType; + } + + public FileParameter(string parameterName, byte[] fileData, string fileName, string contentType = null) : this(parameterName, new MemoryStream(fileData), fileName, contentType) + { + } + + public Stream FileData { get; } + public string FileName { get; } + public string ParameterName { get; } + public string ContentType { get; } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiException.mustache new file mode 100644 index 00000000000..ff5b4476a08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/ApiException.mustache @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; + +namespace {{clientPackage}}; + +/// +/// API Exception +/// +public class {{exceptionTypeName}} : 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; } + + public IReadOnlyDictionary> Headers{get; private set;} + + /// + /// Initializes a new instance of the class. + /// + public {{exceptionTypeName}}() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public {{exceptionTypeName}}(int errorCode, string message) : this(errorCode, message, null, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public {{exceptionTypeName}}(int errorCode, string message, Object errorContent = null, IReadOnlyDictionary> headers = null, Exception original = null) : base(message, original) + { + ErrorCode = errorCode; + ErrorContent = errorContent; + Headers = headers; + } + +} diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/README.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/README.mustache new file mode 100644 index 00000000000..0d10db5b59b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/README.mustache @@ -0,0 +1,148 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Frameworks supported +- .NET 2.0 + + +## Dependencies +- Mono compiler +- Newtonsoft.Json.7.0.1 +- RestSharp.Net2.1.1.11 + +Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh compile-mono.sh` +- [Windows] TODO + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using {{apiPackage}}; +using {{clientPackage}}; +using {{modelPackage}}; +``` + +## Getting Started + +```csharp +using System; +using System.Diagnostics; +using {{apiPackage}}; +using {{clientPackage}}; +using {{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api.mustache new file mode 100644 index 00000000000..af4ebc55023 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api.mustache @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Text; +using System.Threading.Tasks; +using System.CodeDom.Compiler; +using {{clientPackage}}; +{{#hasImport}}using {{modelPackage}}; +{{/hasImport}} + +namespace {{apiPackage}}; + +{{#operations}} +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "{{generateorVersion}}")] +public partial interface I{{classname}} +{ + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/allParams}}/// Operation cancellation token. + /// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} +} + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "{{generateorVersion}}")] +public partial class {{classname}} : {{apiClientBaseTypeName}}, I{{classname}} +{ + /// + /// Initializes a new instance of the class. + /// + /// HttpClient to be used for calls. + /// Base url to be used for calls. + public {{classname}}(HttpClient httpClient, String basePath="{{{basePath}}}") : base(httpClient, basePath) + { + } + + {{#operation}} + /// + public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new {{exceptionTypeName}}(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} + + var path_ = new StringBuilder("{{{path}}}"); + {{#pathParams}}path_ = path_.Replace("{{=<% %>=}}{<% baseName %>}<%={{ }}=%>", ParameterToString({{{paramName}}})); + {{/pathParams}} + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ParameterToString({{paramName}})); // query parameter + {{/queryParams}}{{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ParameterToString({{paramName}})); // header parameter + {{/headerParams}}{{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}}{{#bodyParam}}postBody = {{paramName}}; // http body (model) parameter + {{/bodyParam}} + + {{#returnType}}var response = {{/returnType}}await CallApi{{#returnType}}<{{{returnType}}}>{{/returnType}}(path_.ToString(), HttpMethod.{{#lambda.pascalcase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.pascalcase}}, queryParams, postBody, headerParams, formParams, fileParams, ct);{{#returnType}} + + return response;{{/returnType}} + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api_doc.mustache new file mode 100644 index 00000000000..d8a074e11f3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/api_doc.mustache @@ -0,0 +1,97 @@ +# {{apiPackage}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```csharp +using System; +using System.Diagnostics; +using {{apiPackage}}; +using {{clientPackage}}; +using {{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{returnType}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[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) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/csproj.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/csproj.mustache new file mode 100644 index 00000000000..ec49e420ef9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/csproj.mustache @@ -0,0 +1,22 @@ + + + + {{targetFramework}} + {{clientPackage}} + + + + + {{packageName}} + {{packageVersion}} + {{packageAuthors}} + {{packageCompany}} + {{packageTitle}} + {{packageDescription}} + {{packageCopyright}} + + + + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model.mustache new file mode 100644 index 00000000000..ccfeb77db96 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model.mustache @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +{{#models}} +{{#model}} +namespace {{modelPackage}}; + +/// +/// {{description}} +/// +[GeneratedCode("swagger-codegen", "{{generateorVersion}}")] +public partial class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} +{ + {{#vars}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + [JsonPropertyName("{{baseName}}")] + public {{{datatype}}} {{name}} { get; set; } + + {{/vars}} + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + sb.Append("}\n"); + return sb.ToString(); + } + + {{/model}} + {{/models}} +} diff --git a/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model_doc.mustache new file mode 100644 index 00000000000..e7c3ed75934 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp-dotnet-core/model_doc.mustache @@ -0,0 +1,14 @@ +{{#models}} +{{#model}} +# {{{modelPackage}}}.{{{classname}}} +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}} +{{/models}} diff --git a/samples/client/petstore/csharp-dotnet-core/.swagger-codegen-ignore b/samples/client/petstore/csharp-dotnet-core/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-dotnet-core/.swagger-codegen/VERSION b/samples/client/petstore/csharp-dotnet-core/.swagger-codegen/VERSION new file mode 100644 index 00000000000..717311e32e3 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/.swagger-codegen/VERSION @@ -0,0 +1 @@ +unset \ No newline at end of file diff --git a/samples/client/petstore/csharp-dotnet-core/ApiClient.cs b/samples/client/petstore/csharp-dotnet-core/ApiClient.cs new file mode 100644 index 00000000000..927d5b59f39 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/ApiClient.cs @@ -0,0 +1,405 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Reflection; +using System.Globalization; +using System.Text; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace PetShop; + +/// +/// Base type for API client is mainly responsible for making the HTTP call to the API. +/// +[GeneratedCode("swagger-codegen", "1.0")] +public abstract class PetShopApiClientBase +{ + protected readonly HttpClient _httpClient; + protected readonly string _basePath; + protected readonly JsonSerializerOptions _options; + + /// + /// Initializes a new instance of the class. + /// + /// Client for making http calls. + /// The base path. + /// Serialization settings. + protected PetShopApiClientBase(HttpClient httpClient, string basePath, JsonSerializerOptions options = null) + { + _httpClient = httpClient; + _basePath = basePath; + _options = options ?? JsonSerializerOptions.Default; + } + + protected virtual string ContentType => "application/json-patch+json"; + protected virtual string Accept => "application/json"; + protected virtual IFormatProvider DateTimeFormatForQuery => CultureInfo.CurrentCulture.DateTimeFormat; + + /// + /// Makes the HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// Object to be serialized for http request body. + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Operation cancellation token. + /// Result of request. + protected virtual async Task CallApi( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + CancellationToken ct + ) + { + using (var request = new HttpRequestMessage()) + { + PrepareRequest(path, method, queryParams, body, headerParams, formParams, fileParams, request); + HttpResponseMessage response = null; + try + { + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + + var headers = CollectHeaders(response); + + var status = (int)response.StatusCode; + if (status is >= 200 and < 300) + { + return await ReadObjectResponseAsync(response, headers, ct).ConfigureAwait(false); + } + else + { + var responseData = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + throw new PetShopApiException(status, "The HTTP status code of the response was not expected (" + status + ").", responseData, headers, null); + } + } + finally + { + response?.Dispose(); + } + } + } + + /// + /// Makes the HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// Object to be serialized for http request body. + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Operation cancellation token. + /// Result of request. + protected virtual async Task CallApi( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + CancellationToken ct + ) + { + using (var request = new HttpRequestMessage()) + { + PrepareRequest(path, method, queryParams, body, headerParams, formParams, fileParams, request); + + HttpResponseMessage response = null; + try + { + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + + var headers = CollectHeaders(response); + + var status = (int)response.StatusCode; + if (status is < 200 or >= 300) + { + var responseData = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + throw new PetShopApiException(status, "The HTTP status code of the response was not expected (" + status + ").", responseData, headers, null); + } + } + finally + { + response?.Dispose(); + } + } + } + + private void PrepareRequest( + string path, + HttpMethod method, + Dictionary queryParams, + object body, + Dictionary headerParams, + Dictionary formParams, + Dictionary fileParams, + HttpRequestMessage request + ) + { + request.Method = method; + + // prepare request body + if (body != null) + { + string json; + if (body is string stringBody) + { + json = stringBody; + } + else + { + json = JsonSerializer.Serialize(body, _options); + } + + var content = new StringContent(json); + content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType); + request.Content = content; + } + + //form-data + if (formParams != null && formParams.Count > 0) + { + request.Content = new FormUrlEncodedContent(formParams); + } + + // file sending + if(fileParams != null) + { + using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) + { + foreach(var kvp in fileParams) + { + content.Add(ToStreamContent(kvp.Value)); + } + request.Content = content; + } + } + + // headers + request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(Accept)); + if (headerParams != null) + { + foreach (var kvp in headerParams) + { + request.Headers.Add(kvp.Key, kvp.Value); + } + } + + // build url + var urlBuilder = new StringBuilder(); + if (!string.IsNullOrEmpty(_basePath)) + { + urlBuilder.Append(_basePath); + } + + urlBuilder.Append(path); + + urlBuilder.Append('?'); + if (queryParams != null) + { + foreach (var kvp in queryParams) + { + urlBuilder.Append( + Uri.EscapeDataString(kvp.Key) + ).Append('=') + .Append( + Uri.EscapeDataString( + ConvertToString(kvp.Value, CultureInfo.InvariantCulture) + ) + ).Append('&'); + } + + urlBuilder.Length--; + } + + var url = urlBuilder.ToString(); + request.RequestUri = new Uri(url, UriKind.RelativeOrAbsolute); + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async Task ReadObjectResponseAsync( + HttpResponseMessage response, + IReadOnlyDictionary> headers, + CancellationToken ct + ) + { + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + try + { + return JsonSerializer.Deserialize(responseText, _options); + } + catch (JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new PetShopApiException((int)response.StatusCode, message, responseText, headers, exception); + } + } + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false)) + { + return await JsonSerializer.DeserializeAsync(responseStream, _options, ct); + } + } + catch (JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new PetShopApiException((int)response.StatusCode, message, string.Empty, headers, exception); + } + } + + private string ConvertToString(object value, IFormatProvider cultureInfo) + { + if (value == null) + { + return String.Empty; + } + + if (value is Enum) + { + var name = Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = value.GetType().GetTypeInfo().GetDeclaredField(name); + if (field != null) + { + var attribute = field.GetCustomAttribute(typeof(System.Runtime.Serialization.EnumMemberAttribute)) as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value ?? name; + } + } + + var converted = Convert.ToString(Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted ?? string.Empty; + } + } + else if (value is bool asBool) + { + return Convert.ToString(asBool, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[] asByte) + { + return Convert.ToBase64String(asByte); + } + else if (value is string[] stringArray) + { + return string.Join(",", stringArray); + } + else if (value.GetType().IsArray) + { + var valueArray = (Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); + } + + var result = Convert.ToString(value, cultureInfo); + return result ?? String.Empty; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list of string, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + protected virtual string ParameterToString(object obj) + { + 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(DateTimeFormatForQuery); + if (obj is List list) + return String.Join(",", list.ToArray()); + return Convert.ToString(obj); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public static FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream fs) + { + return new FileParameter(name, stream, Path.GetFileName(fs.Name)); + } + return new FileParameter(name, stream, "no_file_name_provided"); + } + + private static Dictionary> CollectHeaders(HttpResponseMessage response) + { + var headers = new Dictionary>(response.Headers.Count() + response.Content.Headers.Count()); + foreach (var item in response.Headers) + { + headers[item.Key] = item.Value; + } + + foreach (var item in response.Content.Headers) + { + headers[item.Key] = item.Value; + } + + return headers; + } + + private StreamContent ToStreamContent(FileParameter fileParameter) + { + var stream = fileParameter.FileData; + var streamContent = new StreamContent(stream); + + streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(fileParameter.ContentType); + + var dispositionHeader = ContentDispositionHeaderValue.Parse($"form-data; name=\"{fileParameter.ParameterName}\"; filename=\"{fileParameter.FileName}\""); + streamContent.Headers.ContentDisposition = dispositionHeader; + + return streamContent; + } +} + +public class FileParameter +{ + public FileParameter(string parameterName, Stream fileData, string fileName, string contentType = null) + { + ParameterName = parameterName; + FileName = fileName; + FileData = fileData; + ContentType = contentType; + } + + public FileParameter(string parameterName, byte[] fileData, string fileName, string contentType = null) : this(parameterName, new MemoryStream(fileData), fileName, contentType) + { + } + + public Stream FileData { get; } + public string FileName { get; } + public string ParameterName { get; } + public string ContentType { get; } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-dotnet-core/Clients/PetApi.cs b/samples/client/petstore/csharp-dotnet-core/Clients/PetApi.cs new file mode 100644 index 00000000000..f7f851ba8ee --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Clients/PetApi.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Text; +using System.Threading.Tasks; +using System.CodeDom.Compiler; +using PetShop; +using PetShop.Models; + +namespace PetShop.Clients; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial interface IPetApi +{ + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + /// Operation cancellation token. + /// + Task AddPet (Pet body, CancellationToken ct); + /// + /// Deletes a pet + /// + /// Pet id to delete + /// + /// + /// Operation cancellation token. + /// + Task DeletePet (long? petId, string apiKey, CancellationToken ct); + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Status values that need to be considered for filter + /// + /// Operation cancellation token. + /// List<Pet> + Task> FindPetsByStatus (List status, CancellationToken ct); + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// + /// Operation cancellation token. + /// List<Pet> + Task> FindPetsByTags (List tags, CancellationToken ct); + /// + /// Find pet by ID Returns a single pet + /// + /// ID of pet to return + /// + /// Operation cancellation token. + /// Pet + Task GetPetById (long? petId, CancellationToken ct); + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + /// Operation cancellation token. + /// + Task UpdatePet (Pet body, CancellationToken ct); + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + /// + /// Operation cancellation token. + /// + Task UpdatePetWithForm (long? petId, string name, string status, CancellationToken ct); + /// + /// uploads an image + /// + /// ID of pet to update + /// Additional data to pass to server + /// file to upload + /// + /// Operation cancellation token. + /// ApiResponse + Task UploadFile (long? petId, string additionalMetadata, System.IO.Stream _file, CancellationToken ct); +} + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class PetApi : PetShopApiClientBase, IPetApi +{ + /// + /// Initializes a new instance of the class. + /// + /// HttpClient to be used for calls. + /// Base url to be used for calls. + public PetApi(HttpClient httpClient, String basePath="http://petstore.swagger.io/v2") : base(httpClient, basePath) + { + } + + /// + public async Task AddPet(Pet body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling AddPet"); + + + var path_ = new StringBuilder("/pet"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task DeletePet(long? petId, string apiKey, CancellationToken ct) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new PetShopApiException(400, "Missing required parameter 'petId' when calling DeletePet"); + + + var path_ = new StringBuilder("/pet/{petId}"); + path_ = path_.Replace("{petId}", ParameterToString(petId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (apiKey != null) headerParams.Add("api_key", ParameterToString(apiKey)); // header parameter + + await CallApi(path_.ToString(), HttpMethod.Delete, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task> FindPetsByStatus(List status, CancellationToken ct) + { + + // verify the required parameter 'status' is set + if (status == null) throw new PetShopApiException(400, "Missing required parameter 'status' when calling FindPetsByStatus"); + + + var path_ = new StringBuilder("/pet/findByStatus"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (status != null) queryParams.Add("status", ParameterToString(status)); // query parameter + + var response = await CallApi>(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task> FindPetsByTags(List tags, CancellationToken ct) + { + + // verify the required parameter 'tags' is set + if (tags == null) throw new PetShopApiException(400, "Missing required parameter 'tags' when calling FindPetsByTags"); + + + var path_ = new StringBuilder("/pet/findByTags"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (tags != null) queryParams.Add("tags", ParameterToString(tags)); // query parameter + + var response = await CallApi>(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task GetPetById(long? petId, CancellationToken ct) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new PetShopApiException(400, "Missing required parameter 'petId' when calling GetPetById"); + + + var path_ = new StringBuilder("/pet/{petId}"); + path_ = path_.Replace("{petId}", ParameterToString(petId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + var response = await CallApi(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task UpdatePet(Pet body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling UpdatePet"); + + + var path_ = new StringBuilder("/pet"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Put, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task UpdatePetWithForm(long? petId, string name, string status, CancellationToken ct) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new PetShopApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); + + + var path_ = new StringBuilder("/pet/{petId}"); + path_ = path_.Replace("{petId}", ParameterToString(petId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (name != null) formParams.Add("name", ParameterToString(name)); // form parameter + if (status != null) formParams.Add("status", ParameterToString(status)); // form parameter + + await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task UploadFile(long? petId, string additionalMetadata, System.IO.Stream _file, CancellationToken ct) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new PetShopApiException(400, "Missing required parameter 'petId' when calling UploadFile"); + + + var path_ = new StringBuilder("/pet/{petId}/uploadImage"); + path_ = path_.Replace("{petId}", ParameterToString(petId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (additionalMetadata != null) formParams.Add("additionalMetadata", ParameterToString(additionalMetadata)); // form parameter + if (_file != null) fileParams.Add("file", ParameterToFile("file", _file)); + + var response = await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Clients/StoreApi.cs b/samples/client/petstore/csharp-dotnet-core/Clients/StoreApi.cs new file mode 100644 index 00000000000..ff6053bbb4e --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Clients/StoreApi.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Text; +using System.Threading.Tasks; +using System.CodeDom.Compiler; +using PetShop; +using PetShop.Models; + +namespace PetShop.Clients; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial interface IStoreApi +{ + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + /// Operation cancellation token. + /// + Task DeleteOrder (string orderId, CancellationToken ct); + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// + /// Operation cancellation token. + /// Dictionary<string, int?> + Task> GetInventory (CancellationToken ct); + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// + /// Operation cancellation token. + /// Order + Task GetOrderById (long? orderId, CancellationToken ct); + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// + /// Operation cancellation token. + /// Order + Task PlaceOrder (Order body, CancellationToken ct); +} + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class StoreApi : PetShopApiClientBase, IStoreApi +{ + /// + /// Initializes a new instance of the class. + /// + /// HttpClient to be used for calls. + /// Base url to be used for calls. + public StoreApi(HttpClient httpClient, String basePath="http://petstore.swagger.io/v2") : base(httpClient, basePath) + { + } + + /// + public async Task DeleteOrder(string orderId, CancellationToken ct) + { + + // verify the required parameter 'orderId' is set + if (orderId == null) throw new PetShopApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); + + + var path_ = new StringBuilder("/store/order/{orderId}"); + path_ = path_.Replace("{orderId}", ParameterToString(orderId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + await CallApi(path_.ToString(), HttpMethod.Delete, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task> GetInventory(CancellationToken ct) + { + + + var path_ = new StringBuilder("/store/inventory"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + var response = await CallApi>(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task GetOrderById(long? orderId, CancellationToken ct) + { + + // verify the required parameter 'orderId' is set + if (orderId == null) throw new PetShopApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); + + + var path_ = new StringBuilder("/store/order/{orderId}"); + path_ = path_.Replace("{orderId}", ParameterToString(orderId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + var response = await CallApi(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task PlaceOrder(Order body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling PlaceOrder"); + + + var path_ = new StringBuilder("/store/order"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + var response = await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Clients/UserApi.cs b/samples/client/petstore/csharp-dotnet-core/Clients/UserApi.cs new file mode 100644 index 00000000000..0aff3d2d8c6 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Clients/UserApi.cs @@ -0,0 +1,277 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Text; +using System.Threading.Tasks; +using System.CodeDom.Compiler; +using PetShop; +using PetShop.Models; + +namespace PetShop.Clients; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial interface IUserApi +{ + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + /// Operation cancellation token. + /// + Task CreateUser (User body, CancellationToken ct); + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + /// Operation cancellation token. + /// + Task CreateUsersWithArrayInput (List body, CancellationToken ct); + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + /// Operation cancellation token. + /// + Task CreateUsersWithListInput (List body, CancellationToken ct); + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + /// Operation cancellation token. + /// + Task DeleteUser (string username, CancellationToken ct); + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// Operation cancellation token. + /// User + Task GetUserByName (string username, CancellationToken ct); + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// + /// Operation cancellation token. + /// string + Task LoginUser (string username, string password, CancellationToken ct); + /// + /// Logs out current logged in user session + /// + /// + /// Operation cancellation token. + /// + Task LogoutUser (CancellationToken ct); + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted + /// Updated user object + /// + /// Operation cancellation token. + /// + Task UpdateUser (string username, User body, CancellationToken ct); +} + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class UserApi : PetShopApiClientBase, IUserApi +{ + /// + /// Initializes a new instance of the class. + /// + /// HttpClient to be used for calls. + /// Base url to be used for calls. + public UserApi(HttpClient httpClient, String basePath="http://petstore.swagger.io/v2") : base(httpClient, basePath) + { + } + + /// + public async Task CreateUser(User body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling CreateUser"); + + + var path_ = new StringBuilder("/user"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task CreateUsersWithArrayInput(List body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling CreateUsersWithArrayInput"); + + + var path_ = new StringBuilder("/user/createWithArray"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task CreateUsersWithListInput(List body, CancellationToken ct) + { + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling CreateUsersWithListInput"); + + + var path_ = new StringBuilder("/user/createWithList"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Post, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task DeleteUser(string username, CancellationToken ct) + { + + // verify the required parameter 'username' is set + if (username == null) throw new PetShopApiException(400, "Missing required parameter 'username' when calling DeleteUser"); + + + var path_ = new StringBuilder("/user/{username}"); + path_ = path_.Replace("{username}", ParameterToString(username)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + await CallApi(path_.ToString(), HttpMethod.Delete, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task GetUserByName(string username, CancellationToken ct) + { + + // verify the required parameter 'username' is set + if (username == null) throw new PetShopApiException(400, "Missing required parameter 'username' when calling GetUserByName"); + + + var path_ = new StringBuilder("/user/{username}"); + path_ = path_.Replace("{username}", ParameterToString(username)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + var response = await CallApi(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task LoginUser(string username, string password, CancellationToken ct) + { + + // verify the required parameter 'username' is set + if (username == null) throw new PetShopApiException(400, "Missing required parameter 'username' when calling LoginUser"); + + // verify the required parameter 'password' is set + if (password == null) throw new PetShopApiException(400, "Missing required parameter 'password' when calling LoginUser"); + + + var path_ = new StringBuilder("/user/login"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + if (username != null) queryParams.Add("username", ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", ParameterToString(password)); // query parameter + + var response = await CallApi(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + + return response; + } + + /// + public async Task LogoutUser(CancellationToken ct) + { + + + var path_ = new StringBuilder("/user/logout"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + + await CallApi(path_.ToString(), HttpMethod.Get, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + + /// + public async Task UpdateUser(string username, User body, CancellationToken ct) + { + + // verify the required parameter 'username' is set + if (username == null) throw new PetShopApiException(400, "Missing required parameter 'username' when calling UpdateUser"); + + // verify the required parameter 'body' is set + if (body == null) throw new PetShopApiException(400, "Missing required parameter 'body' when calling UpdateUser"); + + + var path_ = new StringBuilder("/user/{username}"); + path_ = path_.Replace("{username}", ParameterToString(username)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + object postBody = null; + + postBody = body; // http body (model) parameter + + await CallApi(path_.ToString(), HttpMethod.Put, queryParams, postBody, headerParams, formParams, fileParams, ct); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Amount.cs b/samples/client/petstore/csharp-dotnet-core/Models/Amount.cs new file mode 100644 index 00000000000..604a8543f5f --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Amount.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// some description +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Amount +{ + /// + /// some description + /// + /// some description + [JsonPropertyName("value")] + public double? Value { get; set; } + + /// + /// Gets or Sets Currency + /// + [JsonPropertyName("currency")] + public Currency Currency { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/ApiResponse.cs b/samples/client/petstore/csharp-dotnet-core/Models/ApiResponse.cs new file mode 100644 index 00000000000..631c7d10434 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/ApiResponse.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// Describes the result of uploading an image resource +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class ApiResponse +{ + /// + /// Gets or Sets Code + /// + [JsonPropertyName("code")] + public int? Code { get; set; } + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Gets or Sets Message + /// + [JsonPropertyName("message")] + public string Message { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Category.cs b/samples/client/petstore/csharp-dotnet-core/Models/Category.cs new file mode 100644 index 00000000000..4e89f8d60fe --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Category.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// A category for a pet +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Category +{ + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Currency.cs b/samples/client/petstore/csharp-dotnet-core/Models/Currency.cs new file mode 100644 index 00000000000..a288dc77744 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Currency.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// some description +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Currency +{ + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Currency {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Order.cs b/samples/client/petstore/csharp-dotnet-core/Models/Order.cs new file mode 100644 index 00000000000..a88af215895 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Order.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// An order for a pets from the pet store +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Order +{ + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [JsonPropertyName("petId")] + public long? PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [JsonPropertyName("quantity")] + public int? Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + [JsonPropertyName("shipDate")] + public DateTime? ShipDate { get; set; } + + /// + /// Order Status + /// + /// Order Status + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool? Complete { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Pet.cs b/samples/client/petstore/csharp-dotnet-core/Models/Pet.cs new file mode 100644 index 00000000000..5a96f8fb33c --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Pet.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// A pet for sale in the pet store +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Pet +{ + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// + /// Gets or Sets Category + /// + [JsonPropertyName("category")] + public Category Category { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [JsonPropertyName("tags")] + public List Tags { get; set; } + + /// + /// pet status in the store + /// + /// pet status in the store + [JsonPropertyName("status")] + public string Status { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/Tag.cs b/samples/client/petstore/csharp-dotnet-core/Models/Tag.cs new file mode 100644 index 00000000000..708a0b3ae59 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/Tag.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// A tag for a pet +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class Tag +{ + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/Models/User.cs b/samples/client/petstore/csharp-dotnet-core/Models/User.cs new file mode 100644 index 00000000000..35d9ddcb06f --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/Models/User.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; +using System.Text.Json.Serialization; + +namespace PetShop.Models; + +/// +/// A User who is purchasing from the pet store +/// +[GeneratedCode("swagger-codegen", "1.0")] +public partial class User +{ + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// + /// Gets or Sets Username + /// + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// Gets or Sets FirstName + /// + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Gets or Sets Email + /// + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [JsonPropertyName("phone")] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [JsonPropertyName("userStatus")] + public int? UserStatus { get; set; } + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/PetShop.csproj b/samples/client/petstore/csharp-dotnet-core/PetShop.csproj new file mode 100644 index 00000000000..811158e884d --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/PetShop.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + PetShop + + + + + PetShop + 1.0.0 + Swagger + Swagger + Swagger Library + A library generated from a Swagger doc + No Copyright + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp-dotnet-core/PetShop.sln b/samples/client/petstore/csharp-dotnet-core/PetShop.sln new file mode 100644 index 00000000000..f854d4f5628 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/PetShop.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34701.34 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PetShop", "PetShop.csproj", "{5CA9B75F-9613-4596-A295-B0078CB67D58}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5CA9B75F-9613-4596-A295-B0078CB67D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CA9B75F-9613-4596-A295-B0078CB67D58}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CA9B75F-9613-4596-A295-B0078CB67D58}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CA9B75F-9613-4596-A295-B0078CB67D58}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FFD86F22-1869-4930-810F-02356674E14A} + EndGlobalSection +EndGlobal diff --git a/samples/client/petstore/csharp-dotnet-core/PetShopApiException.cs b/samples/client/petstore/csharp-dotnet-core/PetShopApiException.cs new file mode 100644 index 00000000000..04158443f0c --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/PetShopApiException.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; + +namespace PetShop; + +/// +/// API Exception +/// +public class PetShopApiException : 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; } + + public IReadOnlyDictionary> Headers{get; private set;} + + /// + /// Initializes a new instance of the class. + /// + public PetShopApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public PetShopApiException(int errorCode, string message) : this(errorCode, message, null, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public PetShopApiException(int errorCode, string message, Object errorContent = null, IReadOnlyDictionary> headers = null, Exception original = null) : base(message, original) + { + ErrorCode = errorCode; + ErrorContent = errorContent; + Headers = headers; + } + +} diff --git a/samples/client/petstore/csharp-dotnet-core/README.md b/samples/client/petstore/csharp-dotnet-core/README.md new file mode 100644 index 00000000000..3f33344bd9e --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/README.md @@ -0,0 +1,134 @@ +# PetShop - the C# library for the Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build package: io.swagger.codegen.languages.CsharpDotnetCoreClientCodegen + + +## Frameworks supported +- .NET 2.0 + + +## Dependencies +- Mono compiler +- Newtonsoft.Json.7.0.1 +- RestSharp.Net2.1.1.11 + +Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh compile-mono.sh` +- [Windows] TODO + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using PetShop.Clients; +using PetShop; +using PetShop.Models; +``` + +## Getting Started + +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class Example + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Add a new pet to the store + apiInstance.AddPet(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + } + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**AddPet**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**DeleteOrder**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [PetShop.Models.Amount](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsAmount.md) + - [PetShop.Models.ApiResponse](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsApiResponse.md) + - [PetShop.Models.Category](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsCategory.md) + - [PetShop.Models.Currency](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsCurrency.md) + - [PetShop.Models.Order](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsOrder.md) + - [PetShop.Models.Pet](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsPet.md) + - [PetShop.Models.Tag](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsTag.md) + - [PetShop.Models.User](E:/Sources/Repos/swagger-gen-cli/swagger-codegen/samples/client/petstore/csharp-dotnet-core/docsUser.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Amount.md b/samples/client/petstore/csharp-dotnet-core/docs/Amount.md new file mode 100644 index 00000000000..5c456d49da0 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Amount.md @@ -0,0 +1,10 @@ +# PetShop.Models.Amount +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Value** | **double?** | some description | +**Currency** | [**Currency**](Currency.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/ApiResponse.md b/samples/client/petstore/csharp-dotnet-core/docs/ApiResponse.md new file mode 100644 index 00000000000..8e3abd6f77a --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/ApiResponse.md @@ -0,0 +1,11 @@ +# PetShop.Models.ApiResponse +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int?** | | [optional] +**Type** | **string** | | [optional] +**Message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Category.md b/samples/client/petstore/csharp-dotnet-core/docs/Category.md new file mode 100644 index 00000000000..ffe59607361 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Category.md @@ -0,0 +1,10 @@ +# PetShop.Models.Category +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**Name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Currency.md b/samples/client/petstore/csharp-dotnet-core/docs/Currency.md new file mode 100644 index 00000000000..29703788679 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Currency.md @@ -0,0 +1,8 @@ +# PetShop.Models.Currency +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Order.md b/samples/client/petstore/csharp-dotnet-core/docs/Order.md new file mode 100644 index 00000000000..4e0b9d7791c --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Order.md @@ -0,0 +1,14 @@ +# PetShop.Models.Order +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**PetId** | **long?** | | [optional] +**Quantity** | **int?** | | [optional] +**ShipDate** | **DateTime?** | | [optional] +**Status** | **string** | Order Status | [optional] +**Complete** | **bool?** | | [optional] [default to false] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Pet.md b/samples/client/petstore/csharp-dotnet-core/docs/Pet.md new file mode 100644 index 00000000000..52396d2ad13 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Pet.md @@ -0,0 +1,14 @@ +# PetShop.Models.Pet +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**Category** | [**Category**](Category.md) | | [optional] +**Name** | **string** | | +**PhotoUrls** | **List<string>** | | +**Tags** | [**List<Tag>**](Tag.md) | | [optional] +**Status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/PetApi.md b/samples/client/petstore/csharp-dotnet-core/docs/PetApi.md new file mode 100644 index 00000000000..ce1431c09ea --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/PetApi.md @@ -0,0 +1,560 @@ +# PetShop.Clients.PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **AddPet** +> void AddPet (Pet body, CancellationToken ct) + +Add a new pet to the store + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class AddPetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Add a new pet to the store + apiInstance.AddPet(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[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) + + +# **DeletePet** +> void DeletePet (long? petId, string apiKey, CancellationToken ct) + +Deletes a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class DeletePetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | Pet id to delete + var apiKey = apiKey_example; // string | (optional) + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| Pet id to delete | + **apiKey** | **string**| | [optional] + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **FindPetsByStatus** +> List FindPetsByStatus (List status, CancellationToken ct) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class FindPetsByStatusExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var status = status_example; // List | Status values that need to be considered for filter + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Finds Pets by status + List<Pet> result = apiInstance.FindPetsByStatus(status, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **List**| Status values that need to be considered for filter | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **FindPetsByTags** +> List FindPetsByTags (List tags, CancellationToken ct) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class FindPetsByTagsExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var tags = new List(); // List | Tags to filter by + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Finds Pets by tags + List<Pet> result = apiInstance.FindPetsByTags(tags, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List**](string.md)| Tags to filter by | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **GetPetById** +> Pet GetPetById (long? petId, CancellationToken ct) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class GetPetByIdExample + { + public void main() + { + + // Configure API key authorization: api_key + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to return + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet to return | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **UpdatePet** +> void UpdatePet (Pet body, CancellationToken ct) + +Update an existing pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class UpdatePetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Update an existing pet + apiInstance.UpdatePet(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[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) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long? petId, string name, string status, CancellationToken ct) + +Updates a pet in the store with form data + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet that needs to be updated + var name = name_example; // string | Updated name of the pet (optional) + var status = status_example; // string | Updated status of the pet (optional) + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet that needs to be updated | + **name** | **string**| Updated name of the pet | [optional] + **status** | **string**| Updated status of the pet | [optional] + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + +[[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) + + +# **UploadFile** +> ApiResponse UploadFile (long? petId, string additionalMetadata, System.IO.Stream _file, CancellationToken ct) + +uploads an image + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class UploadFileExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to update + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + var _file = new System.IO.Stream(); // System.IO.Stream | file to upload (optional) + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, _file, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet to update | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + **_file** | **System.IO.Stream**| file to upload | [optional] + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/StoreApi.md b/samples/client/petstore/csharp-dotnet-core/docs/StoreApi.md new file mode 100644 index 00000000000..917ec297064 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/StoreApi.md @@ -0,0 +1,270 @@ +# PetShop.Clients.StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (string orderId, CancellationToken ct) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class DeleteOrderExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var orderId = orderId_example; // string | ID of the order that needs to be deleted + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **string**| ID of the order that needs to be deleted | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **GetInventory** +> Dictionary GetInventory (CancellationToken ct) + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class GetInventoryExample + { + public void main() + { + + // Configure API key authorization: api_key + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); + + var apiInstance = new StoreApi(); + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Returns pet inventories by status + Dictionary<string, int?> result = apiInstance.GetInventory(ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +**Dictionary** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[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) + + +# **GetOrderById** +> Order GetOrderById (long? orderId, CancellationToken ct) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class GetOrderByIdExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var orderId = 789; // long? | ID of pet that needs to be fetched + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **long?**| ID of pet that needs to be fetched | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **PlaceOrder** +> Order PlaceOrder (Order body, CancellationToken ct) + +Place an order for a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class PlaceOrderExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var body = new Order(); // Order | order placed for purchasing the pet + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(body, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/Tag.md b/samples/client/petstore/csharp-dotnet-core/docs/Tag.md new file mode 100644 index 00000000000..021c6524fd7 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/Tag.md @@ -0,0 +1,10 @@ +# PetShop.Models.Tag +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**Name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/User.md b/samples/client/petstore/csharp-dotnet-core/docs/User.md new file mode 100644 index 00000000000..3b6f8781f07 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/User.md @@ -0,0 +1,16 @@ +# PetShop.Models.User +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**Username** | **string** | | [optional] +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Email** | **string** | | [optional] +**Password** | **string** | | [optional] +**Phone** | **string** | | [optional] +**UserStatus** | **int?** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet-core/docs/UserApi.md b/samples/client/petstore/csharp-dotnet-core/docs/UserApi.md new file mode 100644 index 00000000000..2f167da196c --- /dev/null +++ b/samples/client/petstore/csharp-dotnet-core/docs/UserApi.md @@ -0,0 +1,524 @@ +# PetShop.Clients.UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +# **CreateUser** +> void CreateUser (User body, CancellationToken ct) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class CreateUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new User(); // User | Created user object + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Create user + apiInstance.CreateUser(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List body, CancellationToken ct) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](User.md)| List of user object | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List body, CancellationToken ct) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](User.md)| List of user object | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **DeleteUser** +> void DeleteUser (string username, CancellationToken ct) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class DeleteUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be deleted + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Delete user + apiInstance.DeleteUser(username, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **GetUserByName** +> User GetUserByName (string username, CancellationToken ct) + +Get user by user name + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class GetUserByNameExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **LoginUser** +> string LoginUser (string username, string password, CancellationToken ct) + +Logs user into the system + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class LoginUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The user name for login + var password = password_example; // string | The password for login in clear text + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password, ct); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **LogoutUser** +> void LogoutUser (CancellationToken ct) + +Logs out current logged in user session + + + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class LogoutUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) + + +# **UpdateUser** +> void UpdateUser (string username, User body, CancellationToken ct) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using PetShop.Clients; +using PetShop; +using PetShop.Models; + +namespace Example +{ + public class UpdateUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | name that need to be deleted + var body = new User(); // User | Updated user object + var ct = new CancellationToken(); // CancellationToken | (optional) + + try + { + // Updated user + apiInstance.UpdateUser(username, body, ct); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + **ct** | [**CancellationToken**](.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[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) +