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..13a16747483 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 @@ -80,7 +80,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig 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 d2fd1835f3b..ea0e9ab0786 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -10,36 +10,38 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; - _client = new RestClient(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}} + {{/allParams}} /// public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -52,20 +54,23 @@ namespace {{package}} { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", apiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} // query parameters, if any {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", {{paramName}});{{/queryParams}} // header parameters, if any {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", {{paramName}});{{/headerParams}} // form parameters, if any - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}} {{/formParams}} + {{#bodyParam}} + _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); + {{/bodyParam}} try { - {{#returnType}}IRestResponse response = _client.Execute(_request); - return ({{{returnType}}}) ApiInvoker.deserialize(response.Content, typeof({{{returnType}}})); + {{#returnType}}IRestResponse response = restClient.Execute(_request); + return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}})); //return ((object)response) as {{{returnType}}};{{/returnType}} - {{^returnType}}_client.Execute(_request); + {{^returnType}}restClient.Execute(_request); return;{{/returnType}} } catch (Exception ex) { if(ex != null) { 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; +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(); +namespace {{invokerPackage}} { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// 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 static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// 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 string ParameterToString(object obj) + /// + /// 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 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); - } - + 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) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - 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/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index ec781454cbb..e039513c581 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 @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class PetApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(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 /// @@ -56,10 +58,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -71,7 +76,7 @@ namespace io.swagger.Api { } } - + /// /// Add a new pet to the store /// @@ -95,10 +100,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -110,7 +118,7 @@ namespace io.swagger.Api { } } - + /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// @@ -134,10 +142,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + IRestResponse response = restClient.Execute(_request); + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); //return ((object)response) as List; } catch (Exception ex) { @@ -150,7 +159,7 @@ namespace io.swagger.Api { } } - + /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// @@ -174,10 +183,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + IRestResponse response = restClient.Execute(_request); + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); //return ((object)response) as List; } catch (Exception ex) { @@ -190,7 +200,7 @@ namespace io.swagger.Api { } } - + /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -207,17 +217,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Pet) ApiInvoker.deserialize(response.Content, typeof(Pet)); + IRestResponse response = restClient.Execute(_request); + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); //return ((object)response) as Pet; } catch (Exception ex) { @@ -230,13 +241,13 @@ namespace io.swagger.Api { } } - + /// /// 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) { @@ -249,19 +260,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any - if (Name != null) _request.AddFile("name", Name); - if (Status != null) _request.AddFile("status", Status); + if (Name != null) _request.AddParameter("name", Name); + if (Status != null) _request.AddParameter("status", Status); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -273,12 +285,12 @@ namespace io.swagger.Api { } } - + /// /// Deletes a pet /// /// - /// Pet id to delete + /// Pet id to delete /// public void DeletePet (string ApiKey, long? PetId) { @@ -291,17 +303,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any if (ApiKey != null) _request.AddHeader("api_key", ApiKey); // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -313,13 +326,13 @@ namespace io.swagger.Api { } } - + /// /// 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) { @@ -332,19 +345,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any - if (AdditionalMetadata != null) _request.AddFile("additionalMetadata", AdditionalMetadata); - if (File != null) _request.AddParameter("file", File); + if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", AdditionalMetadata); + if (File != null) _request.AddFile("file", File); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { 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 e921827d94b..6d0b148ea15 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 @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class StoreApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(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 /// @@ -55,10 +57,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Dictionary) ApiInvoker.deserialize(response.Content, typeof(Dictionary)); + IRestResponse response = restClient.Execute(_request); + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); //return ((object)response) as Dictionary; } catch (Exception ex) { @@ -71,7 +74,7 @@ namespace io.swagger.Api { } } - + /// /// Place an order for a pet /// @@ -95,10 +98,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - IRestResponse response = _client.Execute(_request); - return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + IRestResponse response = restClient.Execute(_request); + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); //return ((object)response) as Order; } catch (Exception ex) { @@ -111,7 +117,7 @@ namespace io.swagger.Api { } } - + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// @@ -128,17 +134,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + IRestResponse response = restClient.Execute(_request); + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); //return ((object)response) as Order; } catch (Exception ex) { @@ -151,7 +158,7 @@ namespace io.swagger.Api { } } - + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -168,17 +175,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { 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 dfbede38cfb..7ca6bd5b1fc 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 @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class UserApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(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. /// @@ -56,10 +58,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -71,7 +76,7 @@ namespace io.swagger.Api { } } - + /// /// Creates list of users with given input array /// @@ -95,10 +100,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -110,7 +118,7 @@ namespace io.swagger.Api { } } - + /// /// Creates list of users with given input array /// @@ -134,10 +142,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -149,12 +160,12 @@ namespace io.swagger.Api { } } - + /// /// Logs user into the system /// /// The user name for login - /// The password for login in clear text + /// The password for login in clear text /// public string LoginUser (string Username, string Password) { @@ -174,10 +185,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (string) ApiInvoker.deserialize(response.Content, typeof(string)); + IRestResponse response = restClient.Execute(_request); + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); //return ((object)response) as string; } catch (Exception ex) { @@ -190,7 +202,7 @@ namespace io.swagger.Api { } } - + /// /// Logs out current logged in user session /// @@ -213,10 +225,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -228,7 +241,7 @@ namespace io.swagger.Api { } } - + /// /// Get user by user name /// @@ -245,17 +258,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (User) ApiInvoker.deserialize(response.Content, typeof(User)); + IRestResponse response = restClient.Execute(_request); + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); //return ((object)response) as User; } catch (Exception ex) { @@ -268,12 +282,12 @@ namespace io.swagger.Api { } } - + /// /// 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) { @@ -286,17 +300,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -308,7 +325,7 @@ namespace io.swagger.Api { } } - + /// /// Delete user This can only be done by the logged in user. /// @@ -325,17 +342,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { 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..7b13e16523a 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; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; 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 @@ namespace io.swagger.Model { } -} \ 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..3d67de0a82b 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; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; 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 @@ namespace io.swagger.Model { } -} \ 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..a00f8729d3f 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; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; 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 @@ namespace io.swagger.Model { } -} \ 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..b0c08431472 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; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; 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 @@ namespace io.swagger.Model { } -} \ 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..37931c6fbe4 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; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; 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 @@ namespace io.swagger.Model { } -} \ 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..abdfad1ae3b 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; +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(); +namespace io.swagger.client { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// 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 static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// 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 string ParameterToString(object obj) + /// + /// 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 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); - } - + 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) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - 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); } } } +}