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 969b143c5a0..5060899d498 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 @@ -7,7 +7,7 @@ import java.io.File; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; + protected String invokerPackage = "IO.Swagger.Client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-csharp-client"; protected String artifactVersion = "1.0.0"; @@ -31,8 +31,8 @@ public CSharpClientCodegen() { modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); templateDir = "csharp"; - apiPackage = "io.swagger.Api"; - modelPackage = "io.swagger.Model"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; reservedWords = new HashSet ( Arrays.asList( @@ -80,7 +80,7 @@ public CSharpClientCodegen() { typeMapping.put("double", "double?"); typeMapping.put("number", "double?"); typeMapping.put("Date", "DateTime"); - typeMapping.put("file", "byte[]"); + typeMapping.put("file", "string"); // path to file typeMapping.put("array", "List"); typeMapping.put("map", "Dictionary"); diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 084caf97b9b..f7cc79c5255 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using {{invokerPackage}}; using {{modelPackage}}; {{#imports}} @@ -9,101 +10,73 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } {{#operation}} - + /// /// {{summary}} {{notes}} /// - {{#allParams}}/// {{description}} - {{#hasMore}} {{/hasMore}}{{/allParams}} - /// - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // create path and map variables - var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.ParameterToString({{{paramName}}})){{/pathParams}}; +{{#allParams}} /// {{description}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#requiredParamCount}} - // verify required params are set - if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiException(400, "missing required params"); - } - {{/requiredParamCount}} + {{#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}} - {{#queryParams}}if ({{paramName}} != null){ - queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } - {{/queryParams}} - {{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + {{/pathParams}} + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - - {{#formParams}}if ({{paramName}} != null){ - if({{paramName}} is byte[]) { - formParams.Add("{{baseName}}", {{paramName}}); - } else { - formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - } + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{/bodyParam}} - try { - if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) { - {{#returnType}} - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as {{{returnType}}}; - {{/returnType}} - {{^returnType}} - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - {{/returnType}} - } else { - {{#returnType}} - var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - if (response != null){ - return ({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})); - } - else { - return null; - } - {{/returnType}} - {{^returnType}} - apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - return; - {{/returnType}} - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return {{#returnType}}null{{/returnType}}; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + 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}} + 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 3b371aea9a8..f28eb8de6f7 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -1,21 +1,17 @@ using System; namespace {{invokerPackage}} { + public class ApiException : Exception { - - private int errorCode = 0; - public ApiException() {} + public int ErrorCode { get; set; } - public int ErrorCode { - get - { - return errorCode; - } - } + public ApiException() {} public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; + this.ErrorCode = errorCode; } + } -} \ No newline at end of file + +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache index 4e7f1b6997b..9beebc19231 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache @@ -1,235 +1,81 @@ - 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 readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +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); + } - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// 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, 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); + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - - } - - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + 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 d9ef4ffbedd..a8a3aa3a7a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -2,19 +2,19 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; {{#models}} {{#model}} namespace {{package}} { + [DataContract] public class {{classname}} { {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} + {{#description}}/* {{{description}}} */{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] public {{{datatype}}} {{name}} { get; set; } {{/vars}} - public override string ToString() { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); @@ -27,4 +27,4 @@ namespace {{package}} { } {{/model}} {{/models}} -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/compile.bat index 18a85febb70..1ced2568767 100644 --- a/samples/client/petstore/csharp/compile.bat +++ b/samples/client/petstore/csharp/compile.bat @@ -1,2 +1,2 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/io.swagger.client.dll /recurse:src\*.cs /doc:bin/io.swagger.client.xml \ No newline at end of file +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/IO.Swagger.Client.dll /recurse:src\*.cs /doc:bin/IO.Swagger.Client.xml \ No newline at end of file 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 4f20c0cba45..6a39ce7ba75 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 @@ -1,471 +1,336 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class PetApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Update an existing pet /// /// Pet object that needs to be added to the store - /// - public void UpdatePet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void UpdatePet (Pet Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.PUT); - + // 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 + + - + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); } + + return; } - + /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store - /// - public void AddPet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void AddPet (Pet Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.POST); - + // 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 + - + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); } + + return; } - + /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - - /// - public List FindPetsByStatus (List Status) { - // create path and map variables - var path = "/pet/findByStatus".Replace("{format}","json"); + /// List + public List FindPetsByStatus (List Status) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByStatus", Method.GET); - if (Status != null){ - queryParams.Add("status", apiInvoker.ParameterToString(Status)); + // 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 + + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + + - - try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } - + /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - - /// - public List FindPetsByTags (List Tags) { - // create path and map variables - var path = "/pet/findByTags".Replace("{format}","json"); + /// List + public List FindPetsByTags (List Tags) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByTags", Method.GET); - if (Tags != null){ - queryParams.Add("tags", apiInvoker.ParameterToString(Tags)); + // 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 + + if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + + - - try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } - + /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - - /// - public Pet GetPetById (long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + /// Pet + public Pet GetPetById (long? PetId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + + - try { - if (typeof(Pet) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Pet; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Pet) ApiInvoker.deserialize(response, typeof(Pet)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); } + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); } - + /// /// 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 - + /// Updated name of the pet + /// Updated status of the pet /// - public void UpdatePetWithForm (string PetId, string Name, string Status) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void UpdatePetWithForm (string PetId, string Name, string Status) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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"); - if (Name != null){ - if(Name is byte[]) { - formParams.Add("name", Name); - } else { - formParams.Add("name", apiInvoker.ParameterToString(Name)); - } - } - if (Status != null){ - if(Status is byte[]) { - formParams.Add("status", Status); - } else { - formParams.Add("status", apiInvoker.ParameterToString(Status)); - } + // 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 + _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 + - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); } + + return; } - + /// /// Deletes a pet /// /// - /// Pet id to delete - + /// Pet id to delete /// - public void DeletePet (string ApiKey, long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void DeletePet (string ApiKey, long? PetId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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"); - headerParams.Add("api_key", apiInvoker.ParameterToString(ApiKey)); - + // 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 + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter + + - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); } + + return; } - + /// /// uploads an image /// /// ID of pet to update - /// Additional data to pass to server - /// file to upload - + /// Additional data to pass to server + /// file to upload /// - public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { - // create path and map variables - var path = "/pet/{petId}/uploadImage".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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"); - if (AdditionalMetadata != null){ - if(AdditionalMetadata is byte[]) { - formParams.Add("additionalMetadata", AdditionalMetadata); - } else { - formParams.Add("additionalMetadata", apiInvoker.ParameterToString(AdditionalMetadata)); - } - } - if (File != null){ - if(File is byte[]) { - formParams.Add("file", File); - } else { - formParams.Add("file", apiInvoker.ParameterToString(File)); - } + // 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 + _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); + - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); } + + return; } } 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 2514539e298..5b4236c7a77 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 @@ -1,238 +1,178 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class StoreApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - - /// - public Dictionary GetInventory () { - // create path and map variables - var path = "/store/inventory".Replace("{format}","json"); + /// Dictionary + public Dictionary GetInventory () { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + + + - - try { - if (typeof(Dictionary) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Dictionary; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Dictionary) ApiInvoker.deserialize(response, typeof(Dictionary)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); } + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); } - + /// /// Place an order for a pet /// /// order placed for purchasing the pet - - /// - public Order PlaceOrder (Order Body) { - // create path and map variables - var path = "/store/order".Replace("{format}","json"); + /// Order + public Order PlaceOrder (Order Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + - + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); } + return (Order) ApiInvoker.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 /// /// ID of pet that needs to be fetched - - /// - public Order GetOrderById (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + /// Order + public Order GetOrderById (string OrderId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + + + + - try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); } + return (Order) ApiInvoker.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 /// /// ID of the order that needs to be deleted - /// - public void DeleteOrder (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + public void DeleteOrder (string OrderId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + + + + - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); } + + return; } } 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 4f1f4a1bf19..ff8f23a18b2 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 @@ -1,433 +1,326 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class UserApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Create user This can only be done by the logged in user. /// /// Created user object - /// - public void CreateUser (User Body) { - // create path and map variables - var path = "/user".Replace("{format}","json"); + public void CreateUser (User Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user", Method.POST); - + // 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 + + - + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); } + + return; } - + /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithArrayInput (List Body) { - // create path and map variables - var path = "/user/createWithArray".Replace("{format}","json"); + public void CreateUsersWithArrayInput (List Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default - + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); } + + return; } - + /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithListInput (List Body) { - // create path and map variables - var path = "/user/createWithList".Replace("{format}","json"); + public void CreateUsersWithListInput (List Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + - + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); } + + return; } - + /// /// Logs user into the system /// /// The user name for login - /// The password for login in clear text - - /// - public string LoginUser (string Username, string Password) { - // create path and map variables - var path = "/user/login".Replace("{format}","json"); + /// The password for login in clear text + /// string + public string LoginUser (string Username, string Password) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/login", Method.GET); - if (Username != null){ - queryParams.Add("username", apiInvoker.ParameterToString(Username)); - } - if (Password != null){ - queryParams.Add("password", apiInvoker.ParameterToString(Password)); + // 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 + + if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter + if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + + - - try { - if (typeof(string) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as string; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (string) ApiInvoker.deserialize(response, typeof(string)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); } + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); } - + /// /// Logs out current logged in user session /// - /// - public void LogoutUser () { - // create path and map variables - var path = "/user/logout".Replace("{format}","json"); + public void LogoutUser () { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + + + - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); } + + return; } - + /// /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - - /// - public User GetUserByName (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + /// User + public User GetUserByName (string Username) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + - try { - if (typeof(User) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as User; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (User) ApiInvoker.deserialize(response, typeof(User)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); } + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); } - + /// /// Updated user This can only be done by the logged in user. /// /// name that need to be deleted - /// Updated user object - + /// Updated user object /// - public void UpdateUser (string Username, User Body) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void UpdateUser (string Username, User Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); } + + return; } - + /// /// Delete user This can only be done by the logged in user. /// /// The name that needs to be deleted - /// - public void DeleteUser (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void DeleteUser (string Username) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + 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); + } + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); } + + return; } } 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 bfe1c0c4be8..04867ca365f 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 @@ -2,21 +2,22 @@ using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Category { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); @@ -31,4 +32,4 @@ public override string ToString() { } -} \ No newline at end of file +} 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 20a6d7367dd..cf773a7a150 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 @@ -2,42 +2,42 @@ using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Order { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="petId", EmitDefaultValue=false)] public long? PetId { get; set; } - + [DataMember(Name="quantity", EmitDefaultValue=false)] public int? Quantity { get; set; } - + [DataMember(Name="shipDate", EmitDefaultValue=false)] public DateTime ShipDate { get; set; } - /* Order Status */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - + [DataMember(Name="complete", EmitDefaultValue=false)] public bool? Complete { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); @@ -60,4 +60,4 @@ public override string ToString() { } -} \ No newline at end of file +} 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 b0f3573b78c..41f4081d371 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 @@ -2,42 +2,42 @@ using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Pet { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="category", EmitDefaultValue=false)] public Category Category { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - + [DataMember(Name="photoUrls", EmitDefaultValue=false)] public List PhotoUrls { get; set; } - + [DataMember(Name="tags", EmitDefaultValue=false)] public List Tags { get; set; } - /* pet status in the store */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); @@ -60,4 +60,4 @@ public override string ToString() { } -} \ No newline at end of file +} 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 2fbf7070050..44b6ae29297 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 @@ -2,21 +2,22 @@ using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Tag { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); @@ -31,4 +32,4 @@ public override string ToString() { } -} \ No newline at end of file +} 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 146ba13c768..0fb3bfc86ce 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 @@ -2,52 +2,52 @@ using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class User { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="username", EmitDefaultValue=false)] public string Username { get; set; } - + [DataMember(Name="firstName", EmitDefaultValue=false)] public string FirstName { get; set; } - + [DataMember(Name="lastName", EmitDefaultValue=false)] public string LastName { get; set; } - + [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } - + [DataMember(Name="password", EmitDefaultValue=false)] public string Password { get; set; } - + [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } - /* User Status */ - + [DataMember(Name="userStatus", EmitDefaultValue=false)] public int? UserStatus { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); @@ -74,4 +74,4 @@ public override string ToString() { } -} \ No newline at end of file +} 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 01648d1607c..7c4a7934681 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,21 +1,17 @@ using System; -namespace io.swagger.client { +namespace IO.Swagger.Client { + public class ApiException : Exception { - - private int errorCode = 0; - public ApiException() {} + public int ErrorCode { get; set; } - public int ErrorCode { - get - { - return errorCode; - } - } + public ApiException() {} public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; + this.ErrorCode = errorCode; } + } -} \ No newline at end of file + +} 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 index ee2c5b1d889..144027b2314 100644 --- 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 @@ -1,235 +1,81 @@ - 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 readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +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); + } - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// 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, 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); + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - - } - - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + catch (Exception e) { + throw new ApiException(500, e.Message); } } } +}