diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java index afba07c95666..abac0db5d9fc 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -41,9 +41,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put("invokerPackage", invokerPackage); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.cs")); - supportingFiles.add(new SupportingFile("apiException.mustache", + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache new file mode 100644 index 000000000000..c5b72977cf5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; + +namespace {{invokerPackage}} { + /// + /// API client is mainly responible for making the HTTP call to the API backend + /// + public class ApiClient { + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="{{basePath}}") { + this.basePath = basePath; + this.restClient = new RestClient(this.basePath); + } + + /// + /// Gets or sets the base path. + /// + /// The base path. + public string basePath { get; set; } + + /// + /// Gets or sets the RestClient + /// + /// The RestClient. + public RestClient restClient { get; set; } + + private Dictionary defaultHeaderMap = new Dictionary(); + + public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { + + var request = new RestRequest(Path, Method); + + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + + // add default header, if any + foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(KeyValuePair param in HeaderParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(KeyValuePair param in QueryParams) + request.AddQueryParameter(param.Key, param.Value); + + // add form parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(KeyValuePair param in FileParams) + request.AddFile(param.Key, param.Value); + + if (PostBody != null) { + request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter + } + + return (Object)restClient.Execute(request); + + } + + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } + + /// + /// Get default header + /// + /// Dictionary of default header + public Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } + + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public string EscapeString(string str) { + return str; + } + + /// + /// if parameter is DateTime, output in ISO8601 format + /// if parameter is a list of string, join the list with "," + /// otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public string ParameterToString(object obj) + { + if (obj is DateTime) { + return ((DateTime)obj).ToString ("u"); + } else if (obj is List) { + return String.Join(",", obj as List); + } else { + return Convert.ToString (obj); + } + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public object Deserialize(string content, Type type) { + if (type.GetType() == typeof(Object)) + return (Object)content; + + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException e) { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public string Serialize(object obj) { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) { + throw new ApiException(500, e.Message); + } + } + + /// + /// Get the API key with prefix + /// + /// Object + /// API key with prefix + public string GetApiKeyWithPrefix (string apiKey) + { + var apiKeyValue = ""; + Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { + return apiKeyPrefix + " " + apiKeyValue; + } else { + return apiKeyValue; + } + } + + /// + /// Update parameters based on authentication + /// + /// Query parameters + /// Header parameters + /// Authentication settings + public void UpdateParamsForAuth(Dictionary QueryParams, Dictionary HeaderParams, string[] AuthSettings) { + if (AuthSettings == null || AuthSettings.Length == 0) + return; + + foreach (string auth in AuthSettings) { + // determine which one to use + switch(auth) { + {{#authMethods}} + case "{{name}}": + {{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + Configuration.password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + break; + } + } + + } + + /// + /// Encode string in base64 format + /// + /// String to be encoded + public static string Base64Encode(string text) { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache new file mode 100644 index 000000000000..1f5c00a356d1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using {{invokerPackage}}; + +namespace {{invokerPackage}} { + /// + /// Represents a set of configuration settings + /// + public class Configuration{ + + /// + /// Gets or sets the API client. This is the default API client for making HTTP calls. + /// + /// The API client. + public static ApiClient apiClient = new ApiClient(); + + /// + /// Gets or sets the username (HTTP basic authentication) + /// + /// The username. + public static String username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication) + /// + /// The password. + public static String password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name + /// + /// The API key. + public static Dictionary apiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name + /// + /// The prefix of the API key. + public static Dictionary apiKeyPrefix = new Dictionary(); + + + } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f7cc79c5255c..8e4a468add3c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -8,35 +8,56 @@ using {{modelPackage}}; namespace {{package}} { {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class {{classname}} { - string basePath; - protected RestClient restClient; - - public {{classname}}(String basePath = "{{basePath}}") - { - this.basePath = basePath; - this.restClient = new RestClient(basePath); - } - /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL + /// an instance of ApiClient (optional) /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public {{classname}}(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Initializes a new instance of the class. /// - public String GetBasePath() { - return this.basePath; + /// + public {{classname}}(String basePath) + { + this.apiClient = new ApiClient(basePath); } + /// + /// Sets the base path of the API client. + /// + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + {{#operation}} - /// /// {{summary}} {{notes}} /// @@ -45,37 +66,41 @@ namespace {{package}} { /// {{#returnType}}{{{returnType}}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); } - {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + {{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index f28eb8de6f75..fd68a46a9767 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -1,13 +1,27 @@ using System; namespace {{invokerPackage}} { - + /// + /// API Exception + /// public class ApiException : Exception { - + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). public int ErrorCode { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The base path. public ApiException() {} + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache deleted file mode 100644 index 9760e44d81a6..000000000000 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using Newtonsoft.Json; - -namespace {{invokerPackage}} { - public class ApiInvoker { - private static Dictionary defaultHeaderMap = new Dictionary(); - - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public static void AddDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } - - /// - /// Get default header - /// - /// Dictionary of default header - public static Dictionary GetDefaultHeader() { - return defaultHeaderMap; - } - - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public static string EscapeString(string str) { - return str; - } - - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public static string ParameterToString(object obj) - { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); - } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object Deserialize(string content, Type type) { - if (type.GetType() == typeof(Object)) - return (Object)content; - - try - { - return JsonConvert.DeserializeObject(content, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - } - - /// - /// Serialize an object into JSON string - /// - /// Object - /// JSON string - public static string Serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - } -} diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index a8a3aa3a7a21..ce0e62de1920 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -3,10 +3,15 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; {{#models}} {{#model}} namespace {{package}} { + + /// + /// {{description}} + /// [DataContract] public class {{classname}} { {{#vars}} @@ -15,6 +20,11 @@ namespace {{package}} { 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"); @@ -24,7 +34,16 @@ namespace {{package}} { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} {{/model}} {{/models}} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 6a39ce7ba753..1f7ddccfb26f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -6,34 +6,55 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class PetApi { - string basePath; - protected RestClient restClient; - - public PetApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.restClient = new RestClient(basePath); - } - /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL + /// an instance of ApiClient (optional) /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public PetApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Initializes a new instance of the class. /// - public String GetBasePath() { - return this.basePath; + /// + public PetApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } - + /// + /// Sets the base path of the API client. + /// + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Update an existing pet @@ -42,26 +63,30 @@ namespace IO.Swagger.Api { /// public void UpdatePet (Pet Body) { - var _request = new RestRequest("/pet", Method.PUT); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); } @@ -69,7 +94,6 @@ namespace IO.Swagger.Api { return; } - /// /// Add a new pet to the store /// @@ -77,26 +101,30 @@ namespace IO.Swagger.Api { /// public void AddPet (Pet Body) { - var _request = new RestRequest("/pet", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); } @@ -104,7 +132,6 @@ namespace IO.Swagger.Api { return; } - /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// @@ -112,33 +139,36 @@ namespace IO.Swagger.Api { /// List public List FindPetsByStatus (List Status) { - var _request = new RestRequest("/pet/findByStatus", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/findByStatus"; + path = path.Replace("{format}", "json"); + - _request.AddUrlSegment("format", "json"); // set format to json by default - - if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); } - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + return (List) apiClient.Deserialize(response.Content, typeof(List)); } - /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// @@ -146,33 +176,36 @@ namespace IO.Swagger.Api { /// List public List FindPetsByTags (List Tags) { - var _request = new RestRequest("/pet/findByTags", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/findByTags"; + path = path.Replace("{format}", "json"); + - _request.AddUrlSegment("format", "json"); // set format to json by default - - if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); } - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + return (List) apiClient.Deserialize(response.Content, typeof(List)); } - /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -180,36 +213,39 @@ namespace IO.Swagger.Api { /// Pet public Pet GetPetById (long? PetId) { - var _request = new RestRequest("/pet/{petId}", Method.GET); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - + // authentication setting, if any + String[] authSettings = new String[] { "api_key", "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); } - return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); + return (Pet) apiClient.Deserialize(response.Content, typeof(Pet)); } - /// /// Updates a pet in the store with form data /// @@ -219,31 +255,35 @@ namespace IO.Swagger.Api { /// public void UpdatePetWithForm (string PetId, string Name, string Status) { - var _request = new RestRequest("/pet/{petId}", Method.POST); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter - if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter + if (Name != null) formParams.Add("name", apiClient.ParameterToString(Name)); // form parameter + if (Status != null) formParams.Add("status", apiClient.ParameterToString(Status)); // form parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); } @@ -251,7 +291,6 @@ namespace IO.Swagger.Api { return; } - /// /// Deletes a pet /// @@ -260,30 +299,34 @@ namespace IO.Swagger.Api { /// public void DeletePet (string ApiKey, long? PetId) { - var _request = new RestRequest("/pet/{petId}", Method.DELETE); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter + if (ApiKey != null) headerParams.Add("api_key", apiClient.ParameterToString(ApiKey)); // header parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); } @@ -291,7 +334,6 @@ namespace IO.Swagger.Api { return; } - /// /// uploads an image /// @@ -301,31 +343,35 @@ namespace IO.Swagger.Api { /// public void UploadFile (long? PetId, string AdditionalMetadata, string File) { - var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}/uploadImage"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter - if (File != null) _request.AddFile("file", File); + if (AdditionalMetadata != null) formParams.Add("additionalMetadata", apiClient.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) fileParams.Add("file", File); + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 5b4236c7a777..a789b3502a05 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -6,34 +6,55 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class StoreApi { - string basePath; - protected RestClient restClient; - - public StoreApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.restClient = new RestClient(basePath); - } - /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL + /// an instance of ApiClient (optional) /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public StoreApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Initializes a new instance of the class. /// - public String GetBasePath() { - return this.basePath; + /// + public StoreApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } - + /// + /// Sets the base path of the API client. + /// + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Returns pet inventories by status Returns a map of status codes to quantities @@ -41,32 +62,35 @@ namespace IO.Swagger.Api { /// Dictionary public Dictionary GetInventory () { - var _request = new RestRequest("/store/inventory", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/store/inventory"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - + // authentication setting, if any + String[] authSettings = new String[] { "api_key" }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); } - return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); + return (Dictionary) apiClient.Deserialize(response.Content, typeof(Dictionary)); } - /// /// Place an order for a pet /// @@ -74,33 +98,36 @@ namespace IO.Swagger.Api { /// Order public Order PlaceOrder (Order Body) { - var _request = new RestRequest("/store/order", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/store/order"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); } - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } - /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// @@ -108,36 +135,39 @@ namespace IO.Swagger.Api { /// Order public Order GetOrderById (string OrderId) { - var _request = new RestRequest("/store/order/{orderId}", Method.GET); - // verify the required parameter 'OrderId' is set if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter - + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); } - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } - /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -145,29 +175,33 @@ namespace IO.Swagger.Api { /// public void DeleteOrder (string OrderId) { - var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); - // verify the required parameter 'OrderId' is set if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter - + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index ff8f23a18b2e..35de41c22578 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -6,34 +6,55 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class UserApi { - string basePath; - protected RestClient restClient; - - public UserApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.restClient = new RestClient(basePath); - } - /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL + /// an instance of ApiClient (optional) /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public UserApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Initializes a new instance of the class. /// - public String GetBasePath() { - return this.basePath; + /// + public UserApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } - + /// + /// Sets the base path of the API client. + /// + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Create user This can only be done by the logged in user. @@ -42,26 +63,30 @@ namespace IO.Swagger.Api { /// public void CreateUser (User Body) { - var _request = new RestRequest("/user", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); } @@ -69,7 +94,6 @@ namespace IO.Swagger.Api { return; } - /// /// Creates list of users with given input array /// @@ -77,26 +101,30 @@ namespace IO.Swagger.Api { /// public void CreateUsersWithArrayInput (List Body) { - var _request = new RestRequest("/user/createWithArray", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/createWithArray"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); } @@ -104,7 +132,6 @@ namespace IO.Swagger.Api { return; } - /// /// Creates list of users with given input array /// @@ -112,26 +139,30 @@ namespace IO.Swagger.Api { /// public void CreateUsersWithListInput (List Body) { - var _request = new RestRequest("/user/createWithList", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/createWithList"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); } @@ -139,7 +170,6 @@ namespace IO.Swagger.Api { return; } - /// /// Logs user into the system /// @@ -148,59 +178,66 @@ namespace IO.Swagger.Api { /// string public string LoginUser (string Username, string Password) { - var _request = new RestRequest("/user/login", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/login"; + path = path.Replace("{format}", "json"); + - _request.AddUrlSegment("format", "json"); // set format to json by default - - if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter - if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter + if (Password != null) queryParams.Add("password", apiClient.ParameterToString(Password)); // query parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); } - return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); + return (string) apiClient.Deserialize(response.Content, typeof(string)); } - /// /// Logs out current logged in user session /// /// public void LogoutUser () { - var _request = new RestRequest("/user/logout", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/logout"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); } @@ -208,7 +245,6 @@ namespace IO.Swagger.Api { return; } - /// /// Get user by user name /// @@ -216,36 +252,39 @@ namespace IO.Swagger.Api { /// User public User GetUserByName (string Username) { - var _request = new RestRequest("/user/{username}", Method.GET); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter - + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); } - return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); + return (User) apiClient.Deserialize(response.Content, typeof(User)); } - /// /// Updated user This can only be done by the logged in user. /// @@ -254,30 +293,34 @@ namespace IO.Swagger.Api { /// public void UpdateUser (string Username, User Body) { - var _request = new RestRequest("/user/{username}", Method.PUT); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - + + // authentication setting, if any + String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); } @@ -285,7 +328,6 @@ namespace IO.Swagger.Api { return; } - /// /// Delete user This can only be done by the logged in user. /// @@ -293,29 +335,33 @@ namespace IO.Swagger.Api { /// public void DeleteUser (string Username) { - var _request = new RestRequest("/user/{username}", Method.DELETE); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter - + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index 04867ca365f2..74121762af91 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Category { @@ -18,6 +23,11 @@ namespace IO.Swagger.Model { 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"); @@ -29,7 +39,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs index a387133dfffa..7451619050c8 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Order { @@ -38,6 +43,11 @@ namespace IO.Swagger.Model { 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"); @@ -57,7 +67,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs index 41f4081d371c..0bfba35b1e37 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Pet { @@ -38,6 +43,11 @@ namespace IO.Swagger.Model { 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"); @@ -57,7 +67,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index 44b6ae292971..53901491a471 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Tag { @@ -18,6 +23,11 @@ namespace IO.Swagger.Model { 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"); @@ -29,7 +39,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs index 0fb3bfc86cec..e58d0296a061 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class User { @@ -48,6 +53,11 @@ namespace IO.Swagger.Model { 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"); @@ -71,7 +81,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs new file mode 100644 index 000000000000..39d59f063f2f --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; + +namespace IO.Swagger.Client { + /// + /// API client is mainly responible for making the HTTP call to the API backend + /// + public class ApiClient { + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="http://petstore.swagger.io/v2") { + this.basePath = basePath; + this.restClient = new RestClient(this.basePath); + } + + /// + /// Gets or sets the base path. + /// + /// The base path. + public string basePath { get; set; } + + /// + /// Gets or sets the RestClient + /// + /// The RestClient. + public RestClient restClient { get; set; } + + private Dictionary defaultHeaderMap = new Dictionary(); + + public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { + + var request = new RestRequest(Path, Method); + + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + + // add default header, if any + foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(KeyValuePair param in HeaderParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(KeyValuePair param in QueryParams) + request.AddQueryParameter(param.Key, param.Value); + + // add form parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(KeyValuePair param in FileParams) + request.AddFile(param.Key, param.Value); + + if (PostBody != null) { + request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter + } + + return (Object)restClient.Execute(request); + + } + + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } + + /// + /// Get default header + /// + /// Dictionary of default header + public Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } + + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public string EscapeString(string str) { + return str; + } + + /// + /// if parameter is DateTime, output in ISO8601 format + /// if parameter is a list of string, join the list with "," + /// otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public string ParameterToString(object obj) + { + if (obj is DateTime) { + return ((DateTime)obj).ToString ("u"); + } else if (obj is List) { + return String.Join(",", obj as List); + } else { + return Convert.ToString (obj); + } + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public object Deserialize(string content, Type type) { + if (type.GetType() == typeof(Object)) + return (Object)content; + + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException e) { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public string Serialize(object obj) { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) { + throw new ApiException(500, e.Message); + } + } + + /// + /// Get the API key with prefix + /// + /// Object + /// API key with prefix + public string GetApiKeyWithPrefix (string apiKey) + { + var apiKeyValue = ""; + Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { + return apiKeyPrefix + " " + apiKeyValue; + } else { + return apiKeyValue; + } + } + + /// + /// Update parameters based on authentication + /// + /// Query parameters + /// Header parameters + /// Authentication settings + public void UpdateParamsForAuth(Dictionary QueryParams, Dictionary HeaderParams, string[] AuthSettings) { + if (AuthSettings == null || AuthSettings.Length == 0) + return; + + foreach (string auth in AuthSettings) { + // determine which one to use + switch(auth) { + + case "api_key": + HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key"); + + break; + + case "petstore_auth": + + //TODO support oauth + break; + + default: + //TODO show warning about security definition not found + break; + } + } + + } + + /// + /// Encode string in base64 format + /// + /// String to be encoded + public static string Base64Encode(string text) { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + + } +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index 7c4a7934681b..691c2cd3fa24 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,13 +1,27 @@ using System; namespace IO.Swagger.Client { - + /// + /// API Exception + /// public class ApiException : Exception { - + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). public int ErrorCode { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The base path. public ApiException() {} + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs deleted file mode 100644 index 8bb364728353..000000000000 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using Newtonsoft.Json; - -namespace IO.Swagger.Client { - public class ApiInvoker { - private static Dictionary defaultHeaderMap = new Dictionary(); - - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public static void AddDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } - - /// - /// Get default header - /// - /// Dictionary of default header - public static Dictionary GetDefaultHeader() { - return defaultHeaderMap; - } - - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public static string EscapeString(string str) { - return str; - } - - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public static string ParameterToString(object obj) - { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); - } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object Deserialize(string content, Type type) { - if (type.GetType() == typeof(Object)) - return (Object)content; - - try - { - return JsonConvert.DeserializeObject(content, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - } - - /// - /// Serialize an object into JSON string - /// - /// Object - /// JSON string - public static string Serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - } -} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs new file mode 100644 index 000000000000..4e7975e3ad0b --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using IO.Swagger.Client; + +namespace IO.Swagger.Client { + /// + /// Represents a set of configuration settings + /// + public class Configuration{ + + /// + /// Gets or sets the API client. This is the default API client for making HTTP calls. + /// + /// The API client. + public static ApiClient apiClient = new ApiClient(); + + /// + /// Gets or sets the username (HTTP basic authentication) + /// + /// The username. + public static String username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication) + /// + /// The password. + public static String password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name + /// + /// The API key. + public static Dictionary apiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name + /// + /// The prefix of the API key. + public static Dictionary apiKeyPrefix = new Dictionary(); + + + } +}