From 5c057e13062908b28b261d62672fa418280d592f Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 12 Apr 2015 19:21:22 +0800 Subject: [PATCH 1/6] refactor csharp client using restsharp, getpetbyid working --- .../src/main/resources/csharp/api.mustache | 77 ++--- .../src/main/csharp/io/swagger/Api/PetApi.cs | 326 ++++++------------ .../main/csharp/io/swagger/Api/StoreApi.cs | 153 +++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 285 ++++++--------- 4 files changed, 286 insertions(+), 555 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 084caf97b9b5..d2fd1835f3b1 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}} @@ -10,10 +11,12 @@ namespace {{package}} { public class {{classname}} { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -39,65 +42,33 @@ namespace {{package}} { {{#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}}; - // 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}} + {{#requiredParams}} + // verify required param {{paramName}} is set + if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); + {{/requiredParams}} - {{#queryParams}}if ({{paramName}} != null){ - queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - {{/queryParams}} - - {{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - {{/headerParams}} - - {{#formParams}}if ({{paramName}} != null){ - if({{paramName}} is byte[]) { - formParams.Add("{{baseName}}", {{paramName}}); - } else { - formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#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}} 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) { + {{#returnType}}IRestResponse response = _client.Execute(_request); + return ({{{returnType}}}) ApiInvoker.deserialize(response.Content, typeof({{{returnType}}})); + //return ((object)response) as {{{returnType}}};{{/returnType}} + {{^returnType}}_client.Execute(_request); + return;{{/returnType}} + } catch (Exception ex) { + if(ex != null) { return {{#returnType}}null{{/returnType}}; } else { 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 4f20c0cba455..ec781454cbb3 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,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class PetApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -40,35 +43,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.PUT); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -88,35 +82,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -136,43 +121,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/findByStatus".Replace("{format}","json"); - // 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)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Status != null) _request.AddParameter("status", Status); + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + //return ((object)response) as List; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -192,43 +161,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/findByTags".Replace("{format}","json"); - // 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)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Tags != null) _request.AddParameter("tags", Tags); + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + //return ((object)response) as List; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -248,40 +201,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (Pet) ApiInvoker.deserialize(response.Content, typeof(Pet)); + //return ((object)response) as Pet; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -303,49 +243,28 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - - 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)); - } - } + // form parameters, if any + if (Name != null) _request.AddFile("name", Name); + if (Status != null) _request.AddFile("status", Status); 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -366,36 +285,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - - headerParams.Add("api_key", apiInvoker.ParameterToString(ApiKey)); - - + // header parameters, if any + if (ApiKey != null) _request.AddHeader("api_key", ApiKey); + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -417,49 +326,28 @@ namespace io.swagger.Api { // 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(); + var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - - 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)); - } - } + // form parameters, if any + if (AdditionalMetadata != null) _request.AddFile("additionalMetadata", AdditionalMetadata); + if (File != null) _request.AddParameter("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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { 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 2514539e2984..e921827d94b2 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,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class StoreApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -39,40 +42,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/inventory".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/inventory", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (Dictionary) ApiInvoker.deserialize(response.Content, typeof(Dictionary)); + //return ((object)response) as Dictionary; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -92,40 +82,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + //return ((object)response) as Order; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -145,40 +122,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + //return ((object)response) as Order; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -198,35 +162,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { 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 4f1f4a1bf197..dfbede38cfb4 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,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class UserApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -40,35 +43,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -88,35 +82,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/createWithArray".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithArray", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -136,35 +121,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/createWithList".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithList", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -185,46 +161,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/login".Replace("{format}","json"); - // 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)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Username != null) _request.AddParameter("username", Username); if (Password != null) _request.AddParameter("password", Password); + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (string) ApiInvoker.deserialize(response.Content, typeof(string)); + //return ((object)response) as string; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -243,35 +200,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/logout".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/logout", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -291,40 +239,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + IRestResponse response = _client.Execute(_request); + return (User) ApiInvoker.deserialize(response.Content, typeof(User)); + //return ((object)response) as User; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -345,35 +280,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.PUT); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -393,35 +319,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any 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) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { From 8818c209df2d9dd49a6a40f2ae8bec348ad9c062 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 28 Apr 2015 23:48:29 +0800 Subject: [PATCH 2/6] udpate csharp client with restsharp --- .../languages/CSharpClientCodegen.java | 2 +- .../src/main/resources/csharp/api.mustache | 43 +-- .../main/resources/csharp/apiInvoker.mustache | 288 ++++-------------- .../src/main/resources/csharp/model.mustache | 10 +- .../src/main/csharp/io/swagger/Api/PetApi.cs | 102 ++++--- .../main/csharp/io/swagger/Api/StoreApi.cs | 58 ++-- .../src/main/csharp/io/swagger/Api/UserApi.cs | 88 +++--- .../main/csharp/io/swagger/Model/Category.cs | 9 +- .../src/main/csharp/io/swagger/Model/Order.cs | 18 +- .../src/main/csharp/io/swagger/Model/Pet.cs | 18 +- .../src/main/csharp/io/swagger/Model/Tag.cs | 9 +- .../src/main/csharp/io/swagger/Model/User.cs | 22 +- .../csharp/io/swagger/client/ApiInvoker.cs | 288 ++++-------------- 13 files changed, 347 insertions(+), 608 deletions(-) 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 969b143c5a02..13a167474837 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 d2fd1835f3b1..ea0e9ab07864 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 4e7f1b6997bb..9beebc192314 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 d9ef4ffbedd0..a8a3aa3a7a21 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 ec781454cbb3..e039513c581c 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 e921827d94b2..6d0b148ea150 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 dfbede38cfb4..7ca6bd5b1fce 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 bfe1c0c4be82..7b13e16523aa 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 20a6d7367ddc..3d67de0a82b8 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 b0f3573b78c3..a00f8729d3f9 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 2fbf70700504..b0c08431472a 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 146ba13c7683..37931c6fbe47 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 ee2c5b1d889a..abdfad1ae3b8 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); } } } +} From 96d837274ea8d51699771c6c48195a03b19b408d Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 29 Apr 2015 10:43:57 +0800 Subject: [PATCH 3/6] udpate csharp template with better comment and ParameterToString --- .../src/main/resources/csharp/api.mustache | 24 +++--- .../src/main/csharp/io/swagger/Api/PetApi.cs | 81 ++++++------------- .../main/csharp/io/swagger/Api/StoreApi.cs | 32 ++------ .../src/main/csharp/io/swagger/Api/UserApi.cs | 77 +++++------------- 4 files changed, 63 insertions(+), 151 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index ea0e9ab07864..493a5a4de7c4 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -40,10 +40,9 @@ namespace {{package}} { /// /// {{summary}} {{notes}} /// - {{#allParams}}/// {{description}} - {{/allParams}} - /// - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { +{{#allParams}} /// {{description}} +{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); @@ -52,18 +51,17 @@ namespace {{package}} { if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); {{/requiredParams}} - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - {{#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.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}} + {{#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) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}}));{{/isFile}} // form parameter {{/formParams}} {{#bodyParam}} - _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); + _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // HTTP request body (model) {{/bodyParam}} try { 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 e039513c581c..52f676319660 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 @@ -39,7 +39,6 @@ namespace io.swagger.Api { /// Update an existing pet /// /// Pet object that needs to be added to the store - /// public void UpdatePet (Pet Body) { // create path and map variables @@ -49,17 +48,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -81,7 +76,6 @@ namespace io.swagger.Api { /// 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 @@ -91,17 +85,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -123,7 +113,6 @@ namespace io.swagger.Api { /// 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 @@ -133,14 +122,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Status != null) _request.AddParameter("status", Status); - // header parameters, if any + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + - // form parameters, if any @@ -164,7 +150,6 @@ namespace io.swagger.Api { /// 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 @@ -174,14 +159,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Tags != null) _request.AddParameter("tags", Tags); - // header parameters, if any + if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + - // form parameters, if any @@ -205,7 +187,6 @@ namespace io.swagger.Api { /// 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 @@ -215,14 +196,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -248,7 +226,6 @@ namespace io.swagger.Api { /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet - /// public void UpdatePetWithForm (string PetId, string Name, string Status) { // create path and map variables @@ -258,16 +235,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - // header parameters, if any - // form parameters, if any - if (Name != null) _request.AddParameter("name", Name); - if (Status != null) _request.AddParameter("status", Status); + + if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter @@ -291,7 +265,6 @@ namespace io.swagger.Api { /// /// /// Pet id to delete - /// public void DeletePet (string ApiKey, long? PetId) { // create path and map variables @@ -301,14 +274,12 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter - // header parameters, if any - if (ApiKey != null) _request.AddHeader("api_key", ApiKey); - // form parameters, if any @@ -333,7 +304,6 @@ namespace io.swagger.Api { /// ID of pet to update /// Additional data to pass to server /// file to upload - /// public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { // create path and map variables @@ -343,16 +313,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - // header parameters, if any - // form parameters, if any - if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", AdditionalMetadata); - if (File != null) _request.AddFile("file", File); + + if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) _request.AddFile("file", File); // form parameter 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 6d0b148ea150..4aadd02e9cc3 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 @@ -38,7 +38,6 @@ namespace io.swagger.Api { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// public Dictionary GetInventory () { // create path and map variables @@ -48,14 +47,10 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - // header parameters, if any - // form parameters, if any @@ -79,7 +74,6 @@ namespace io.swagger.Api { /// Place an order for a pet /// /// order placed for purchasing the pet - /// public Order PlaceOrder (Order Body) { // create path and map variables @@ -89,17 +83,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -122,7 +112,6 @@ 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 /// /// ID of pet that needs to be fetched - /// public Order GetOrderById (string OrderId) { // create path and map variables @@ -132,14 +121,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); - // query parameters, if any + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -163,7 +149,6 @@ 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 /// /// ID of the order that needs to be deleted - /// public void DeleteOrder (string OrderId) { // create path and map variables @@ -173,14 +158,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); - // query parameters, if any + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any 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 7ca6bd5b1fce..154dd099ba90 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 @@ -39,7 +39,6 @@ namespace io.swagger.Api { /// 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 @@ -49,17 +48,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -81,7 +76,6 @@ namespace io.swagger.Api { /// Creates list of users with given input array /// /// List of user object - /// public void CreateUsersWithArrayInput (List Body) { // create path and map variables @@ -91,17 +85,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -123,7 +113,6 @@ namespace io.swagger.Api { /// Creates list of users with given input array /// /// List of user object - /// public void CreateUsersWithListInput (List Body) { // create path and map variables @@ -133,17 +122,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -176,14 +161,12 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Username != null) _request.AddParameter("username", Username); if (Password != null) _request.AddParameter("password", Password); - // header parameters, if any + if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter + if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + - // form parameters, if any @@ -206,7 +189,6 @@ namespace io.swagger.Api { /// /// Logs out current logged in user session /// - /// public void LogoutUser () { // create path and map variables @@ -216,14 +198,10 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - // header parameters, if any - // form parameters, if any @@ -246,8 +224,6 @@ namespace io.swagger.Api { /// 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)); @@ -256,14 +232,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -288,7 +261,6 @@ namespace io.swagger.Api { /// /// name that need to be deleted /// Updated user object - /// public void UpdateUser (string Username, User Body) { // create path and map variables @@ -298,17 +270,14 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any - - // header parameters, if any - - // form parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -330,7 +299,6 @@ namespace io.swagger.Api { /// 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 @@ -340,14 +308,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any From e7b170bf3ca890bfab6abf80c9d4464b4f4bef4c Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 29 Apr 2015 16:27:08 +0800 Subject: [PATCH 4/6] better comment on csharp api, add ParameterToString to handle date --- .../src/main/resources/csharp/api.mustache | 21 +++-- .../src/main/csharp/io/swagger/Api/PetApi.cs | 77 ++++++++----------- .../main/csharp/io/swagger/Api/StoreApi.cs | 42 +++++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 75 ++++++++---------- 4 files changed, 93 insertions(+), 122 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 493a5a4de7c4..c524d7ed3291 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -41,15 +41,16 @@ namespace {{package}} { /// {{summary}} {{notes}} /// {{#allParams}} /// {{description}} -{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#requiredParams}} - // verify required param {{paramName}} is set - if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); - {{/requiredParams}} + {{#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}} _request.AddUrlSegment("format", "json"); // set format to json by default {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter @@ -58,17 +59,15 @@ namespace {{package}} { {{/queryParams}} {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}}));{{/isFile}} // form parameter + {{#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 request body (model) + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter {{/bodyParam}} try { + // make the HTTP request {{#returnType}}IRestResponse response = restClient.Execute(_request); - return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}})); - //return ((object)response) as {{{returnType}}};{{/returnType}} - {{^returnType}}restClient.Execute(_request); + return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}restClient.Execute(_request); return;{{/returnType}} } catch (Exception ex) { if(ex != null) { 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 52f676319660..850d9fc5c546 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 @@ -40,9 +40,7 @@ namespace io.swagger.Api { /// /// 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) { var _request = new RestRequest("/pet", Method.PUT); @@ -53,12 +51,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -77,9 +74,7 @@ namespace io.swagger.Api { /// /// 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) { var _request = new RestRequest("/pet", Method.POST); @@ -90,12 +85,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -113,10 +107,8 @@ namespace io.swagger.Api { /// 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) { var _request = new RestRequest("/pet/findByStatus", Method.GET); @@ -131,10 +123,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - //return ((object)response) as List; - } catch (Exception ex) { if(ex != null) { return null; @@ -150,10 +141,8 @@ namespace io.swagger.Api { /// 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) { var _request = new RestRequest("/pet/findByTags", Method.GET); @@ -168,10 +157,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - //return ((object)response) as List; - } catch (Exception ex) { if(ex != null) { return null; @@ -187,14 +175,15 @@ namespace io.swagger.Api { /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -205,10 +194,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); - //return ((object)response) as Pet; - } catch (Exception ex) { if(ex != null) { return null; @@ -227,13 +215,14 @@ namespace io.swagger.Api { /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -246,7 +235,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -266,13 +255,14 @@ namespace io.swagger.Api { /// /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -284,7 +274,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -305,13 +295,14 @@ namespace io.swagger.Api { /// 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)); + 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -319,12 +310,12 @@ namespace io.swagger.Api { if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter - if (File != null) _request.AddFile("file", File); // form parameter + if (File != null) _request.AddFile("file", File); try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { 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 4aadd02e9cc3..98b1b5f65267 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 @@ -38,10 +38,8 @@ namespace io.swagger.Api { /// /// 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 () { var _request = new RestRequest("/store/inventory", Method.GET); @@ -55,10 +53,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); - //return ((object)response) as Dictionary; - } catch (Exception ex) { if(ex != null) { return null; @@ -74,10 +71,8 @@ namespace io.swagger.Api { /// 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) { var _request = new RestRequest("/store/order", Method.POST); @@ -88,15 +83,13 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - //return ((object)response) as Order; - } catch (Exception ex) { if(ex != null) { return null; @@ -112,14 +105,15 @@ 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 /// /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter @@ -130,10 +124,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - //return ((object)response) as Order; - } catch (Exception ex) { if(ex != null) { return null; @@ -150,13 +143,14 @@ namespace io.swagger.Api { /// /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter @@ -167,7 +161,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { 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 154dd099ba90..d7ccf0e94298 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 @@ -40,9 +40,7 @@ namespace io.swagger.Api { /// /// Created user object /// - public void CreateUser (User Body) { - // create path and map variables - var path = "/user".Replace("{format}","json"); + public void CreateUser (User Body) { var _request = new RestRequest("/user", Method.POST); @@ -53,12 +51,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -77,9 +74,7 @@ namespace io.swagger.Api { /// /// 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) { var _request = new RestRequest("/user/createWithArray", Method.POST); @@ -90,12 +85,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -114,9 +108,7 @@ namespace io.swagger.Api { /// /// 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) { var _request = new RestRequest("/user/createWithList", Method.POST); @@ -127,12 +119,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -151,11 +142,8 @@ namespace io.swagger.Api { /// /// 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"); + /// string + public string LoginUser (string Username, string Password) { var _request = new RestRequest("/user/login", Method.GET); @@ -171,10 +159,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); - //return ((object)response) as string; - } catch (Exception ex) { if(ex != null) { return null; @@ -190,9 +177,7 @@ namespace io.swagger.Api { /// 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 () { var _request = new RestRequest("/user/logout", Method.GET); @@ -206,7 +191,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -224,13 +209,15 @@ namespace io.swagger.Api { /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -241,10 +228,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); - //return ((object)response) as User; - } catch (Exception ex) { if(ex != null) { return null; @@ -262,13 +248,14 @@ namespace io.swagger.Api { /// name that need to be deleted /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -276,12 +263,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -300,13 +286,14 @@ namespace io.swagger.Api { /// /// 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) { 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"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -317,7 +304,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { From 2f5f2b367b18773d5f6324c4ad564d073770d8f9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 12 May 2015 12:45:59 +0800 Subject: [PATCH 5/6] update package name to confirm to csharp convention, fix default header --- .../languages/CSharpClientCodegen.java | 6 +-- .../src/main/resources/csharp/api.mustache | 6 +++ samples/client/petstore/csharp/compile.bat | 2 +- .../src/main/csharp/io/swagger/Api/PetApi.cs | 54 +++++++++++++++++-- .../main/csharp/io/swagger/Api/StoreApi.cs | 30 +++++++++-- .../src/main/csharp/io/swagger/Api/UserApi.cs | 54 +++++++++++++++++-- .../main/csharp/io/swagger/Model/Category.cs | 2 +- .../src/main/csharp/io/swagger/Model/Order.cs | 2 +- .../src/main/csharp/io/swagger/Model/Pet.cs | 2 +- .../src/main/csharp/io/swagger/Model/Tag.cs | 2 +- .../src/main/csharp/io/swagger/Model/User.cs | 2 +- .../csharp/io/swagger/client/ApiException.cs | 2 +- .../csharp/io/swagger/client/ApiInvoker.cs | 2 +- 13 files changed, 146 insertions(+), 20 deletions(-) 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 13a167474837..5060899d4980 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.util.*; 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 class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig 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( diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index c524d7ed3291..6e06087c1ae2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -52,6 +52,12 @@ namespace {{package}} { if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter {{/pathParams}} diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/compile.bat index 18a85febb708..1ced25687676 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 850d9fc5c546..91e650b2baed 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,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class PetApi { string basePath; @@ -46,6 +46,12 @@ namespace io.swagger.Api { + // 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 @@ -80,6 +86,12 @@ namespace io.swagger.Api { + // 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 @@ -114,6 +126,12 @@ namespace io.swagger.Api { + // 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 @@ -148,6 +166,12 @@ namespace io.swagger.Api { + // 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 @@ -185,6 +209,12 @@ namespace io.swagger.Api { 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 @@ -224,6 +254,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -264,6 +300,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -304,6 +346,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter 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 98b1b5f65267..1f4b4441ae1b 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,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class StoreApi { string basePath; @@ -45,6 +45,12 @@ namespace io.swagger.Api { + // 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 @@ -78,6 +84,12 @@ namespace io.swagger.Api { + // 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 @@ -115,6 +127,12 @@ namespace io.swagger.Api { 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 @@ -152,6 +170,12 @@ namespace io.swagger.Api { 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 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 d7ccf0e94298..1dd08f7c697a 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,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class UserApi { string basePath; @@ -46,6 +46,12 @@ namespace io.swagger.Api { + // 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 @@ -80,6 +86,12 @@ namespace io.swagger.Api { + // 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 @@ -114,6 +126,12 @@ namespace io.swagger.Api { + // 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 @@ -149,6 +167,12 @@ namespace io.swagger.Api { + // 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 @@ -183,6 +207,12 @@ namespace io.swagger.Api { + // 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 @@ -219,6 +249,12 @@ namespace io.swagger.Api { 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 @@ -257,6 +293,12 @@ namespace io.swagger.Api { 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 @@ -295,6 +337,12 @@ namespace io.swagger.Api { 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 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 7b13e16523aa..04867ca365f2 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 @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Category { 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 3d67de0a82b8..cf773a7a1505 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 @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Order { 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 a00f8729d3f9..41f4081d371c 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 @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Pet { 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 b0c08431472a..44b6ae292971 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 @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Tag { 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 37931c6fbe47..0fb3bfc86cec 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 @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class User { 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 01648d1607cd..ffa49217bb88 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,6 +1,6 @@ using System; -namespace io.swagger.client { +namespace IO.Swagger.Client { public class ApiException : Exception { private int errorCode = 0; 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 abdfad1ae3b8..144027b2314e 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 @@ -6,7 +6,7 @@ using System.Net; using System.Text; using Newtonsoft.Json; -namespace io.swagger.client { +namespace IO.Swagger.Client { public class ApiInvoker { private static Dictionary defaultHeaderMap = new Dictionary(); From c12673a40765c2c3592073106ea815b44e464647 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 14 May 2015 14:16:12 +0800 Subject: [PATCH 6/6] fix error handling for 4xx, 5xx returned by server --- .../src/main/resources/csharp/api.mustache | 18 +-- .../resources/csharp/apiException.mustache | 18 +-- .../src/main/csharp/io/swagger/Api/PetApi.cs | 133 ++++++----------- .../main/csharp/io/swagger/Api/StoreApi.cs | 65 +++------ .../src/main/csharp/io/swagger/Api/UserApi.cs | 134 ++++++------------ .../csharp/io/swagger/client/ApiException.cs | 18 +-- 6 files changed, 132 insertions(+), 254 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 6e06087c1ae2..f7cc79c5255c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -70,19 +70,13 @@ namespace {{package}} { {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter {{/bodyParam}} - try { - // make the HTTP request - {{#returnType}}IRestResponse response = restClient.Execute(_request); - return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}restClient.Execute(_request); - return;{{/returnType}} - } catch (Exception ex) { - if(ex != null) { - 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 3b371aea9a8c..f28eb8de6f75 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 int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ 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 91e650b2baed..6a39ce7ba753 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 @@ -60,18 +60,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -100,18 +95,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -140,18 +130,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -180,18 +164,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -223,18 +201,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -270,18 +242,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -315,18 +282,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -362,18 +324,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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 1f4b4441ae1b..5b4236c7a777 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 @@ -58,18 +58,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -98,18 +92,12 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -141,18 +129,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -184,18 +166,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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 1dd08f7c697a..ff8f23a18b2e 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 @@ -60,18 +60,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -100,18 +95,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -140,18 +130,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -182,18 +167,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -220,18 +199,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -263,18 +237,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); - } catch (Exception ex) { - if(ex != null) { - 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)); } @@ -308,18 +276,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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; } @@ -351,18 +314,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - 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/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index ffa49217bb88..7c4a7934681b 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 { + public class ApiException : Exception { - - private int errorCode = 0; + + public int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ No newline at end of file + +}