From f807e34b2b57524feec76dff18eb5662b4309154 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 25 May 2015 18:21:17 +0800 Subject: [PATCH 1/4] refactor csharp (no compile error) --- .../src/main/resources/csharp/api.mustache | 37 ++-- .../main/resources/csharp/apiInvoker.mustache | 58 ++++- .../src/main/csharp/io/swagger/Api/PetApi.cs | 204 +++++++++--------- .../main/csharp/io/swagger/Api/StoreApi.cs | 100 ++++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 194 +++++++++-------- .../csharp/io/swagger/client/ApiInvoker.cs | 58 ++++- 6 files changed, 380 insertions(+), 271 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f7cc79c5255c..ee3f326c746b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -10,12 +10,12 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - protected RestClient restClient; + public ApiInvoker apiClient {get; set;} public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; - this.restClient = new RestClient(basePath); + this.apiClient = new ApiInvoker(basePath); } /// @@ -45,37 +45,38 @@ namespace {{package}} { /// {{#returnType}}{{{returnType}}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("{{path}}", Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); } - {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + {{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache index 9760e44d81a6..01406a8add08 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache @@ -5,10 +5,54 @@ using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; +using RestSharp; namespace {{invokerPackage}} { public class ApiInvoker { - private static Dictionary defaultHeaderMap = new Dictionary(); + public ApiInvoker() { + this.basePath = "{{basePath}}"; + } + + public ApiInvoker(String basePath) { + this.basePath = basePath; + } + + public string basePath { get; set; } + public RestClient restClient { get; set; } + private Dictionary defaultHeaderMap = new Dictionary(); + + public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams) { + + var request = new RestRequest(Path, Method); + + // add default header, if any + foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(KeyValuePair param in HeaderParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(KeyValuePair param in QueryParams) + request.AddUrlSegment(param.Key, param.Value); + + // add form parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddFile(param.Key, param.Value); + + if (PostBody == null) { + request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter + } + + return (Object)restClient.Execute(request); + + } /// /// Add default header @@ -16,7 +60,7 @@ namespace {{invokerPackage}} { /// Header field name /// Header field value /// - public static void AddDefaultHeader(string key, string value) { + public void AddDefaultHeader(string key, string value) { defaultHeaderMap.Add(key, value); } @@ -24,7 +68,7 @@ namespace {{invokerPackage}} { /// Get default header /// /// Dictionary of default header - public static Dictionary GetDefaultHeader() { + public Dictionary GetDefaultHeader() { return defaultHeaderMap; } @@ -33,7 +77,7 @@ namespace {{invokerPackage}} { /// /// String to be escaped /// Escaped string - public static string EscapeString(string str) { + public string EscapeString(string str) { return str; } @@ -42,7 +86,7 @@ namespace {{invokerPackage}} { /// /// The parameter (header, path, query, form) /// Formatted string - public static string ParameterToString(object obj) + public string ParameterToString(object obj) { return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); } @@ -53,7 +97,7 @@ namespace {{invokerPackage}} { /// JSON string /// Object type /// Object representation of the JSON string - public static object Deserialize(string content, Type type) { + public object Deserialize(string content, Type type) { if (type.GetType() == typeof(Object)) return (Object)content; @@ -71,7 +115,7 @@ namespace {{invokerPackage}} { /// /// Object /// JSON string - public static string Serialize(object obj) { + public string Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : 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 6a39ce7ba753..054cb1bc204b 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,12 +8,12 @@ namespace IO.Swagger.Api { public class PetApi { string basePath; - protected RestClient restClient; + public ApiInvoker apiClient {get; set;} public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.restClient = new RestClient(basePath); + this.apiClient = new ApiInvoker(basePath); } /// @@ -42,26 +42,27 @@ namespace IO.Swagger.Api { /// public void UpdatePet (Pet Body) { - var _request = new RestRequest("/pet", Method.PUT); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet", Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); } @@ -77,26 +78,27 @@ namespace IO.Swagger.Api { /// public void AddPet (Pet Body) { - var _request = new RestRequest("/pet", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); } @@ -112,30 +114,31 @@ namespace IO.Swagger.Api { /// List public List FindPetsByStatus (List Status) { - var _request = new RestRequest("/pet/findByStatus", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default + var path = "/pet/findByStatus"; + path = path.Replace("{format}", "json"); - if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/findByStatus", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); } - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + return (List) apiClient.Deserialize(response.Content, typeof(List)); } @@ -146,30 +149,31 @@ namespace IO.Swagger.Api { /// List public List FindPetsByTags (List Tags) { - var _request = new RestRequest("/pet/findByTags", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default + var path = "/pet/findByTags"; + path = path.Replace("{format}", "json"); - if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/findByTags", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); } - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + return (List) apiClient.Deserialize(response.Content, typeof(List)); } @@ -180,33 +184,34 @@ namespace IO.Swagger.Api { /// Pet public Pet GetPetById (long? PetId) { - var _request = new RestRequest("/pet/{petId}", Method.GET); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); } - return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); + return (Pet) apiClient.Deserialize(response.Content, typeof(Pet)); } @@ -219,31 +224,32 @@ namespace IO.Swagger.Api { /// public void UpdatePetWithForm (string PetId, string Name, string Status) { - var _request = new RestRequest("/pet/{petId}", Method.POST); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter - if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter + if (Name != null) formParams.Add("name", apiClient.ParameterToString(Name)); // form parameter + if (Status != null) formParams.Add("status", apiClient.ParameterToString(Status)); // form parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); } @@ -260,30 +266,31 @@ namespace IO.Swagger.Api { /// public void DeletePet (string ApiKey, long? PetId) { - var _request = new RestRequest("/pet/{petId}", Method.DELETE); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter + if (ApiKey != null) headerParams.Add("api_key", apiClient.ParameterToString(ApiKey)); // header parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); } @@ -301,31 +308,32 @@ namespace IO.Swagger.Api { /// public void UploadFile (long? PetId, string AdditionalMetadata, string File) { - var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); - // verify the required parameter 'PetId' is set if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/pet/{petId}/uploadImage"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - - if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter - if (File != null) _request.AddFile("file", File); + if (AdditionalMetadata != null) formParams.Add("additionalMetadata", apiClient.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) fileParams.Add("file", File); // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}/uploadImage", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 5b4236c7a777..9d10a095c447 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,12 +8,12 @@ namespace IO.Swagger.Api { public class StoreApi { string basePath; - protected RestClient restClient; + public ApiInvoker apiClient {get; set;} public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.restClient = new RestClient(basePath); + this.apiClient = new ApiInvoker(basePath); } /// @@ -41,29 +41,30 @@ namespace IO.Swagger.Api { /// Dictionary public Dictionary GetInventory () { - var _request = new RestRequest("/store/inventory", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default + var path = "/store/inventory"; + path = path.Replace("{format}", "json"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/store/inventory", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); } - return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); + return (Dictionary) apiClient.Deserialize(response.Content, typeof(Dictionary)); } @@ -74,30 +75,31 @@ namespace IO.Swagger.Api { /// Order public Order PlaceOrder (Order Body) { - var _request = new RestRequest("/store/order", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/store/order"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); } - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } @@ -108,33 +110,34 @@ namespace IO.Swagger.Api { /// Order public Order GetOrderById (string OrderId) { - var _request = new RestRequest("/store/order/{orderId}", Method.GET); - // verify the required parameter 'OrderId' is set if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order/{orderId}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); } - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } @@ -145,29 +148,30 @@ namespace IO.Swagger.Api { /// public void DeleteOrder (string OrderId) { - var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); - // verify the required parameter 'OrderId' is set if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order/{orderId}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index ff8f23a18b2e..c225f45496de 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,12 +8,12 @@ namespace IO.Swagger.Api { public class UserApi { string basePath; - protected RestClient restClient; + public ApiInvoker apiClient {get; set;} public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.restClient = new RestClient(basePath); + this.apiClient = new ApiInvoker(basePath); } /// @@ -42,26 +42,27 @@ namespace IO.Swagger.Api { /// public void CreateUser (User Body) { - var _request = new RestRequest("/user", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); } @@ -77,26 +78,27 @@ namespace IO.Swagger.Api { /// public void CreateUsersWithArrayInput (List Body) { - var _request = new RestRequest("/user/createWithArray", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/createWithArray"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/createWithArray", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); } @@ -112,26 +114,27 @@ namespace IO.Swagger.Api { /// public void CreateUsersWithListInput (List Body) { - var _request = new RestRequest("/user/createWithList", Method.POST); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/createWithList"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/createWithList", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); } @@ -148,31 +151,32 @@ namespace IO.Swagger.Api { /// string public string LoginUser (string Username, string Password) { - var _request = new RestRequest("/user/login", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default + var path = "/user/login"; + path = path.Replace("{format}", "json"); - if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter - if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter + if (Password != null) queryParams.Add("password", apiClient.ParameterToString(Password)); // query parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/login", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); } - return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); + return (string) apiClient.Deserialize(response.Content, typeof(string)); } @@ -182,25 +186,26 @@ namespace IO.Swagger.Api { /// public void LogoutUser () { - var _request = new RestRequest("/user/logout", Method.GET); - - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default + var path = "/user/logout"; + path = path.Replace("{format}", "json"); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/logout", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); } @@ -216,33 +221,34 @@ namespace IO.Swagger.Api { /// User public User GetUserByName (string Username) { - var _request = new RestRequest("/user/{username}", Method.GET); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); } - return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); + return (User) apiClient.Deserialize(response.Content, typeof(User)); } @@ -254,30 +260,31 @@ namespace IO.Swagger.Api { /// public void UpdateUser (string Username, User Body) { - var _request = new RestRequest("/user/{username}", Method.PUT); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + postBody = apiClient.Serialize(Body); // http body (model) parameter // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); } @@ -293,29 +300,30 @@ namespace IO.Swagger.Api { /// public void DeleteUser (string Username) { - var _request = new RestRequest("/user/{username}", Method.DELETE); - // verify the required parameter 'Username' is set if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + // make the HTTP request - IRestResponse response = restClient.Execute(_request); + IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs index 8bb364728353..ce5cf0263eb6 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 @@ -5,10 +5,54 @@ using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; +using RestSharp; namespace IO.Swagger.Client { public class ApiInvoker { - private static Dictionary defaultHeaderMap = new Dictionary(); + public ApiInvoker() { + this.basePath = "http://petstore.swagger.io/v2"; + } + + public ApiInvoker(String basePath) { + this.basePath = basePath; + } + + public string basePath { get; set; } + public RestClient restClient { get; set; } + private Dictionary defaultHeaderMap = new Dictionary(); + + public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams) { + + var request = new RestRequest(Path, Method); + + // add default header, if any + foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(KeyValuePair param in HeaderParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(KeyValuePair param in QueryParams) + request.AddUrlSegment(param.Key, param.Value); + + // add form parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(KeyValuePair param in FormParams) + request.AddFile(param.Key, param.Value); + + if (PostBody == null) { + request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter + } + + return (Object)restClient.Execute(request); + + } /// /// Add default header @@ -16,7 +60,7 @@ namespace IO.Swagger.Client { /// Header field name /// Header field value /// - public static void AddDefaultHeader(string key, string value) { + public void AddDefaultHeader(string key, string value) { defaultHeaderMap.Add(key, value); } @@ -24,7 +68,7 @@ namespace IO.Swagger.Client { /// Get default header /// /// Dictionary of default header - public static Dictionary GetDefaultHeader() { + public Dictionary GetDefaultHeader() { return defaultHeaderMap; } @@ -33,7 +77,7 @@ namespace IO.Swagger.Client { /// /// String to be escaped /// Escaped string - public static string EscapeString(string str) { + public string EscapeString(string str) { return str; } @@ -42,7 +86,7 @@ namespace IO.Swagger.Client { /// /// The parameter (header, path, query, form) /// Formatted string - public static string ParameterToString(object obj) + public string ParameterToString(object obj) { return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); } @@ -53,7 +97,7 @@ namespace IO.Swagger.Client { /// JSON string /// Object type /// Object representation of the JSON string - public static object Deserialize(string content, Type type) { + public object Deserialize(string content, Type type) { if (type.GetType() == typeof(Object)) return (Object)content; @@ -71,7 +115,7 @@ namespace IO.Swagger.Client { /// /// Object /// JSON string - public static string Serialize(object obj) { + public string Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; From 165efdbdbbe8b79c78f80a88d8270cbacc49aee7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 28 May 2015 18:24:03 +0800 Subject: [PATCH 2/4] rename apiinvoker to apiclient, add configuration, make apiclient an instance --- .../languages/CSharpClientCodegen.java | 8 ++-- ...apiInvoker.mustache => ApiClient.mustache} | 12 +++--- .../resources/csharp/Configuration.mustache | 14 +++++++ .../src/main/resources/csharp/api.mustache | 20 +++++++-- .../src/main/csharp/io/swagger/Api/PetApi.cs | 41 +++++++++++-------- .../main/csharp/io/swagger/Api/StoreApi.cs | 29 ++++++++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 41 +++++++++++-------- .../client/{ApiInvoker.cs => ApiClient.cs} | 12 +++--- .../csharp/io/swagger/client/Configuration.cs | 14 +++++++ 9 files changed, 128 insertions(+), 63 deletions(-) rename modules/swagger-codegen/src/main/resources/csharp/{apiInvoker.mustache => ApiClient.mustache} (92%) create mode 100644 modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache rename samples/client/petstore/csharp/src/main/csharp/io/swagger/client/{ApiInvoker.cs => ApiClient.cs} (92%) create mode 100644 samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs 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 9de427058a12..ceb4849bd2a8 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -41,9 +41,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put("invokerPackage", invokerPackage); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.cs")); - supportingFiles.add(new SupportingFile("apiException.mustache", + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache similarity index 92% rename from modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 01406a8add08..469d5e94c37c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -8,13 +8,15 @@ using Newtonsoft.Json; using RestSharp; namespace {{invokerPackage}} { - public class ApiInvoker { - public ApiInvoker() { + public class ApiClient { + public ApiClient() { this.basePath = "{{basePath}}"; + this.restClient = new RestClient(this.basePath); } - public ApiInvoker(String basePath) { + public ApiClient(String basePath) { this.basePath = basePath; + this.restClient = new RestClient(this.basePath); } public string basePath { get; set; } @@ -43,10 +45,10 @@ namespace {{invokerPackage}} { request.AddParameter(param.Key, param.Value); // add file parameter, if any - foreach(KeyValuePair param in FormParams) + foreach(KeyValuePair param in FileParams) request.AddFile(param.Key, param.Value); - if (PostBody == null) { + if (PostBody != null) { request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache new file mode 100644 index 000000000000..41c371be487d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using {{invokerPackage}}; + +namespace {{invokerPackage}} { + public class Configuration{ + public static ApiClient apiClient = new ApiClient(); + + } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index ee3f326c746b..c78b7461c7e4 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -10,12 +10,25 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - public ApiInvoker apiClient {get; set;} + public ApiClient apiClient {get; set;} public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; - this.apiClient = new ApiInvoker(basePath); + this.apiClient = new ApiClient(basePath); + } + + /// + /// Create a new object + /// + /// an instance of ApiClient + /// + public {{classname}}(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// @@ -36,7 +49,6 @@ namespace {{package}} { } {{#operation}} - /// /// {{summary}} {{notes}} /// @@ -71,7 +83,7 @@ namespace {{package}} { {{/bodyParam}} // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("{{path}}", Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); 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 054cb1bc204b..4c7cd680bed0 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,12 +8,25 @@ namespace IO.Swagger.Api { public class PetApi { string basePath; - public ApiInvoker apiClient {get; set;} + public ApiClient apiClient {get; set;} public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.apiClient = new ApiInvoker(basePath); + this.apiClient = new ApiClient(basePath); + } + + /// + /// Create a new object + /// + /// an instance of ApiClient + /// + public PetApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// @@ -34,7 +47,6 @@ namespace IO.Swagger.Api { } - /// /// Update an existing pet /// @@ -61,7 +73,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet", Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); @@ -70,7 +82,6 @@ namespace IO.Swagger.Api { return; } - /// /// Add a new pet to the store /// @@ -97,7 +108,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); @@ -106,7 +117,6 @@ namespace IO.Swagger.Api { return; } - /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// @@ -133,7 +143,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/findByStatus", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); @@ -141,7 +151,6 @@ namespace IO.Swagger.Api { return (List) apiClient.Deserialize(response.Content, typeof(List)); } - /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// @@ -168,7 +177,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/findByTags", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); @@ -176,7 +185,6 @@ namespace IO.Swagger.Api { return (List) apiClient.Deserialize(response.Content, typeof(List)); } - /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -206,7 +214,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); @@ -214,7 +222,6 @@ namespace IO.Swagger.Api { return (Pet) apiClient.Deserialize(response.Content, typeof(Pet)); } - /// /// Updates a pet in the store with form data /// @@ -248,7 +255,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); @@ -257,7 +264,6 @@ namespace IO.Swagger.Api { return; } - /// /// Deletes a pet /// @@ -289,7 +295,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); @@ -298,7 +304,6 @@ namespace IO.Swagger.Api { return; } - /// /// uploads an image /// @@ -332,7 +337,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/pet/{petId}/uploadImage", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 9d10a095c447..9fa4a528a07c 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,12 +8,25 @@ namespace IO.Swagger.Api { public class StoreApi { string basePath; - public ApiInvoker apiClient {get; set;} + public ApiClient apiClient {get; set;} public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.apiClient = new ApiInvoker(basePath); + this.apiClient = new ApiClient(basePath); + } + + /// + /// Create a new object + /// + /// an instance of ApiClient + /// + public StoreApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// @@ -34,7 +47,6 @@ namespace IO.Swagger.Api { } - /// /// Returns pet inventories by status Returns a map of status codes to quantities /// @@ -59,7 +71,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/store/inventory", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); @@ -67,7 +79,6 @@ namespace IO.Swagger.Api { return (Dictionary) apiClient.Deserialize(response.Content, typeof(Dictionary)); } - /// /// Place an order for a pet /// @@ -94,7 +105,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); @@ -102,7 +113,6 @@ namespace IO.Swagger.Api { return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } - /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// @@ -132,7 +142,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order/{orderId}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); @@ -140,7 +150,6 @@ namespace IO.Swagger.Api { return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } - /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -170,7 +179,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/store/order/{orderId}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index c225f45496de..0d6707d88cfd 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,12 +8,25 @@ namespace IO.Swagger.Api { public class UserApi { string basePath; - public ApiInvoker apiClient {get; set;} + public ApiClient apiClient {get; set;} public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - this.apiClient = new ApiInvoker(basePath); + this.apiClient = new ApiClient(basePath); + } + + /// + /// Create a new object + /// + /// an instance of ApiClient + /// + public UserApi(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } /// @@ -34,7 +47,6 @@ namespace IO.Swagger.Api { } - /// /// Create user This can only be done by the logged in user. /// @@ -61,7 +73,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); @@ -70,7 +82,6 @@ namespace IO.Swagger.Api { return; } - /// /// Creates list of users with given input array /// @@ -97,7 +108,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/createWithArray", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); @@ -106,7 +117,6 @@ namespace IO.Swagger.Api { return; } - /// /// Creates list of users with given input array /// @@ -133,7 +143,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/createWithList", Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); @@ -142,7 +152,6 @@ namespace IO.Swagger.Api { return; } - /// /// Logs user into the system /// @@ -171,7 +180,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/login", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); @@ -179,7 +188,6 @@ namespace IO.Swagger.Api { return (string) apiClient.Deserialize(response.Content, typeof(string)); } - /// /// Logs out current logged in user session /// @@ -204,7 +212,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/logout", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); @@ -213,7 +221,6 @@ namespace IO.Swagger.Api { return; } - /// /// Get user by user name /// @@ -243,7 +250,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); @@ -251,7 +258,6 @@ namespace IO.Swagger.Api { return (User) apiClient.Deserialize(response.Content, typeof(User)); } - /// /// Updated user This can only be done by the logged in user. /// @@ -283,7 +289,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); @@ -292,7 +298,6 @@ namespace IO.Swagger.Api { return; } - /// /// Delete user This can only be done by the logged in user. /// @@ -322,7 +327,7 @@ namespace IO.Swagger.Api { // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi("/user/{username}", Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs similarity index 92% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs rename to samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs index ce5cf0263eb6..2a48e4b30752 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/ApiClient.cs @@ -8,13 +8,15 @@ using Newtonsoft.Json; using RestSharp; namespace IO.Swagger.Client { - public class ApiInvoker { - public ApiInvoker() { + public class ApiClient { + public ApiClient() { this.basePath = "http://petstore.swagger.io/v2"; + this.restClient = new RestClient(this.basePath); } - public ApiInvoker(String basePath) { + public ApiClient(String basePath) { this.basePath = basePath; + this.restClient = new RestClient(this.basePath); } public string basePath { get; set; } @@ -43,10 +45,10 @@ namespace IO.Swagger.Client { request.AddParameter(param.Key, param.Value); // add file parameter, if any - foreach(KeyValuePair param in FormParams) + foreach(KeyValuePair param in FileParams) request.AddFile(param.Key, param.Value); - if (PostBody == null) { + if (PostBody != null) { request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs new file mode 100644 index 000000000000..815bb027c8ff --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using IO.Swagger.Client; + +namespace IO.Swagger.Client { + public class Configuration{ + public static ApiClient apiClient = new ApiClient(); + + } +} From 5f36ad3b75846272db1e20e26a461e4e9f22bc8b Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 29 May 2015 16:43:27 +0800 Subject: [PATCH 3/4] add authentication support --- .../main/resources/csharp/ApiClient.mustache | 81 +++++++++++++++-- .../resources/csharp/Configuration.mustache | 33 +++++++ .../src/main/resources/csharp/api.mustache | 52 ++++++----- .../resources/csharp/apiException.mustache | 18 +++- .../src/main/resources/csharp/model.mustache | 21 ++++- .../src/main/csharp/io/swagger/Api/PetApi.cs | 87 +++++++++++++------ .../main/csharp/io/swagger/Api/StoreApi.cs | 67 +++++++++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 87 +++++++++++++------ .../main/csharp/io/swagger/Model/Category.cs | 21 ++++- .../src/main/csharp/io/swagger/Model/Order.cs | 21 ++++- .../src/main/csharp/io/swagger/Model/Pet.cs | 21 ++++- .../src/main/csharp/io/swagger/Model/Tag.cs | 21 ++++- .../src/main/csharp/io/swagger/Model/User.cs | 21 ++++- .../csharp/io/swagger/client/ApiClient.cs | 86 ++++++++++++++++-- .../csharp/io/swagger/client/ApiException.cs | 18 +++- .../csharp/io/swagger/client/Configuration.cs | 33 +++++++ 16 files changed, 569 insertions(+), 119 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 469d5e94c37c..c841efdc1b5a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -8,26 +8,41 @@ using Newtonsoft.Json; using RestSharp; namespace {{invokerPackage}} { + /// + /// API client is mainly responible for making the HTTP call to the API backend + /// public class ApiClient { - public ApiClient() { - this.basePath = "{{basePath}}"; - this.restClient = new RestClient(this.basePath); - } - public ApiClient(String basePath) { + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="{{basePath}}") { this.basePath = basePath; this.restClient = new RestClient(this.basePath); } + /// + /// Gets or sets the base path. + /// + /// The base path. public string basePath { get; set; } + + /// + /// Gets or sets the RestClient + /// + /// The RestClient. public RestClient restClient { get; set; } + private Dictionary defaultHeaderMap = new Dictionary(); public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, - Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams) { + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { var request = new RestRequest(Path, Method); + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + // add default header, if any foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) request.AddHeader(defaultHeader.Key, defaultHeader.Value); @@ -126,5 +141,59 @@ namespace {{invokerPackage}} { throw new ApiException(500, e.Message); } } + + /// + /// Get the API key with prefix + /// + /// Object + /// API key with prefix + public string GetApiKeyWithPrefix (string apiKey) + { + var apiKeyValue = ""; + Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { + return apiKeyPrefix + " " + apiKeyValue; + } else { + return apiKeyValue; + } + } + + /// + /// Update parameters based on authentication + /// + /// Query parameters + /// Header parameters + /// Authentication settings + public void UpdateParamsForAuth(Dictionary QueryParams, Dictionary HeaderParams, string[] AuthSettings) { + if (AuthSettings == null || AuthSettings.Length == 0) + return; + + foreach (string auth in AuthSettings) { + // determine which one to use + switch(auth) { + {{#authMethods}} + case "{{name}}": + {{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + Configuration.password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + break; + } + } + + } + + /// + /// Encode string in base64 format + /// + /// String to be encoded + public static string Base64Encode(string text) { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + } } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 41c371be487d..1f5c00a356d1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -7,8 +7,41 @@ using System.Text; using {{invokerPackage}}; namespace {{invokerPackage}} { + /// + /// Represents a set of configuration settings + /// public class Configuration{ + + /// + /// Gets or sets the API client. This is the default API client for making HTTP calls. + /// + /// The API client. public static ApiClient apiClient = new ApiClient(); + /// + /// Gets or sets the username (HTTP basic authentication) + /// + /// The username. + public static String username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication) + /// + /// The password. + public static String password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name + /// + /// The API key. + public static Dictionary apiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name + /// + /// The prefix of the API key. + public static Dictionary apiKeyPrefix = new Dictionary(); + + } } diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index c78b7461c7e4..8e4a468add3c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -8,20 +8,14 @@ using {{modelPackage}}; namespace {{package}} { {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class {{classname}} { - string basePath; - public ApiClient apiClient {get; set;} - - public {{classname}}(String basePath = "{{basePath}}") - { - this.basePath = basePath; - this.apiClient = new ApiClient(basePath); - } - /// - /// Create a new object + /// Initializes a new instance of the class. /// - /// an instance of ApiClient + /// an instance of ApiClient (optional) /// public {{classname}}(ApiClient apiClient = null) { if (apiClient == null) { // use the default one in Configuration @@ -32,22 +26,37 @@ namespace {{package}} { } /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public {{classname}}(String basePath) + { + this.apiClient = new ApiClient(basePath); } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Sets the base path of the API client. /// - public String GetBasePath() { - return this.basePath; + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; } + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + {{#operation}} /// /// {{summary}} {{notes}} @@ -82,8 +91,11 @@ namespace {{package}} { {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index f28eb8de6f75..fd68a46a9767 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -1,13 +1,27 @@ using System; namespace {{invokerPackage}} { - + /// + /// API Exception + /// public class ApiException : Exception { - + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). public int ErrorCode { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The base path. public ApiException() {} + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index a8a3aa3a7a21..ce0e62de1920 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -3,10 +3,15 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; {{#models}} {{#model}} namespace {{package}} { + + /// + /// {{description}} + /// [DataContract] public class {{classname}} { {{#vars}} @@ -15,6 +20,11 @@ namespace {{package}} { public {{{datatype}}} {{name}} { get; set; } {{/vars}} + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); @@ -24,7 +34,16 @@ namespace {{package}} { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} {{/model}} {{/models}} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 4c7cd680bed0..1f7ddccfb26f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -6,20 +6,14 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class PetApi { - string basePath; - public ApiClient apiClient {get; set;} - - public PetApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.apiClient = new ApiClient(basePath); - } - /// - /// Create a new object + /// Initializes a new instance of the class. /// - /// an instance of ApiClient + /// an instance of ApiClient (optional) /// public PetApi(ApiClient apiClient = null) { if (apiClient == null) { // use the default one in Configuration @@ -30,22 +24,37 @@ namespace IO.Swagger.Api { } /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public PetApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Sets the base path of the API client. /// - public String GetBasePath() { - return this.basePath; + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; } + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Update an existing pet @@ -72,8 +81,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); @@ -107,8 +119,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); @@ -142,8 +157,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); @@ -176,8 +194,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); @@ -213,8 +234,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "api_key", "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); @@ -254,8 +278,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); @@ -294,8 +321,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); @@ -336,8 +366,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 9fa4a528a07c..a789b3502a05 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -6,20 +6,14 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class StoreApi { - string basePath; - public ApiClient apiClient {get; set;} - - public StoreApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.apiClient = new ApiClient(basePath); - } - /// - /// Create a new object + /// Initializes a new instance of the class. /// - /// an instance of ApiClient + /// an instance of ApiClient (optional) /// public StoreApi(ApiClient apiClient = null) { if (apiClient == null) { // use the default one in Configuration @@ -30,22 +24,37 @@ namespace IO.Swagger.Api { } /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public StoreApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Sets the base path of the API client. /// - public String GetBasePath() { - return this.basePath; + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; } + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Returns pet inventories by status Returns a map of status codes to quantities @@ -70,8 +79,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { "api_key" }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); @@ -104,8 +116,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); @@ -141,8 +156,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); @@ -178,8 +196,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 0d6707d88cfd..35de41c22578 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -6,20 +6,14 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public class UserApi { - string basePath; - public ApiClient apiClient {get; set;} - - public UserApi(String basePath = "http://petstore.swagger.io/v2") - { - this.basePath = basePath; - this.apiClient = new ApiClient(basePath); - } - /// - /// Create a new object + /// Initializes a new instance of the class. /// - /// an instance of ApiClient + /// an instance of ApiClient (optional) /// public UserApi(ApiClient apiClient = null) { if (apiClient == null) { // use the default one in Configuration @@ -30,22 +24,37 @@ namespace IO.Swagger.Api { } /// - /// Sets the endpoint base url for the services being accessed + /// Initializes a new instance of the class. /// - /// Base URL /// - public void SetBasePath(string basePath) { - this.basePath = basePath; + public UserApi(String basePath) + { + this.apiClient = new ApiClient(basePath); } /// - /// Gets the endpoint base url for the services being accessed - /// Base URL + /// Sets the base path of the API client. /// - public String GetBasePath() { - return this.basePath; + /// The base path + public void SetBasePath(String basePath) { + this.apiClient.basePath = basePath; } + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath(String basePath) { + return this.apiClient.basePath; + } + + /// + /// Gets or sets the API client. + /// + /// The API client + public ApiClient apiClient {get; set;} + + /// /// Create user This can only be done by the logged in user. @@ -72,8 +81,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); @@ -107,8 +119,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); @@ -142,8 +157,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); @@ -179,8 +197,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); @@ -211,8 +232,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); @@ -249,8 +273,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); @@ -288,8 +315,11 @@ namespace IO.Swagger.Api { postBody = apiClient.Serialize(Body); // http body (model) parameter + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); @@ -326,8 +356,11 @@ namespace IO.Swagger.Api { + // authentication setting, if any + String[] authSettings = new String[] { }; + // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams); + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index 04867ca365f2..74121762af91 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Category { @@ -18,6 +23,11 @@ namespace IO.Swagger.Model { public string Name { get; set; } + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); @@ -29,7 +39,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs index cf773a7a1505..fd1643dbd29d 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Order { @@ -38,6 +43,11 @@ namespace IO.Swagger.Model { public bool? Complete { get; set; } + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); @@ -57,7 +67,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs index 41f4081d371c..0bfba35b1e37 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Pet { @@ -38,6 +43,11 @@ namespace IO.Swagger.Model { public string Status { get; set; } + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); @@ -57,7 +67,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index 44b6ae292971..53901491a471 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class Tag { @@ -18,6 +23,11 @@ namespace IO.Swagger.Model { public string Name { get; set; } + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); @@ -29,7 +39,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs index 0fb3bfc86cec..e58d0296a061 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -3,8 +3,13 @@ using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; +using Newtonsoft.Json; namespace IO.Swagger.Model { + + /// + /// + /// [DataContract] public class User { @@ -48,6 +53,11 @@ namespace IO.Swagger.Model { public int? UserStatus { get; set; } + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); @@ -71,7 +81,16 @@ namespace IO.Swagger.Model { sb.Append("}\n"); return sb.ToString(); } - } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs index 2a48e4b30752..c801bb1a7361 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs @@ -8,26 +8,41 @@ using Newtonsoft.Json; using RestSharp; namespace IO.Swagger.Client { + /// + /// API client is mainly responible for making the HTTP call to the API backend + /// public class ApiClient { - public ApiClient() { - this.basePath = "http://petstore.swagger.io/v2"; - this.restClient = new RestClient(this.basePath); - } - public ApiClient(String basePath) { + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="http://petstore.swagger.io/v2") { this.basePath = basePath; this.restClient = new RestClient(this.basePath); } + /// + /// Gets or sets the base path. + /// + /// The base path. public string basePath { get; set; } + + /// + /// Gets or sets the RestClient + /// + /// The RestClient. public RestClient restClient { get; set; } + private Dictionary defaultHeaderMap = new Dictionary(); public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, - Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams) { + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { var request = new RestRequest(Path, Method); + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + // add default header, if any foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) request.AddHeader(defaultHeader.Key, defaultHeader.Value); @@ -126,5 +141,64 @@ namespace IO.Swagger.Client { throw new ApiException(500, e.Message); } } + + /// + /// Get the API key with prefix + /// + /// Object + /// API key with prefix + public string GetApiKeyWithPrefix (string apiKey) + { + var apiKeyValue = ""; + Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { + return apiKeyPrefix + " " + apiKeyValue; + } else { + return apiKeyValue; + } + } + + /// + /// Update parameters based on authentication + /// + /// Query parameters + /// Header parameters + /// Authentication settings + public void UpdateParamsForAuth(Dictionary QueryParams, Dictionary HeaderParams, string[] AuthSettings) { + if (AuthSettings == null || AuthSettings.Length == 0) + return; + + foreach (string auth in AuthSettings) { + // determine which one to use + switch(auth) { + + case "api_key": + HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key"); + + break; + + case "petstore_auth": + + //TODO support oauth + break; + + default: + //TODO show warning about security definition not found + break; + } + } + + } + + /// + /// Encode string in base64 format + /// + /// String to be encoded + public static string Base64Encode(string text) { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index 7c4a7934681b..691c2cd3fa24 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,13 +1,27 @@ using System; namespace IO.Swagger.Client { - + /// + /// API Exception + /// public class ApiException : Exception { - + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). public int ErrorCode { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The base path. public ApiException() {} + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs index 815bb027c8ff..4e7975e3ad0b 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs @@ -7,8 +7,41 @@ using System.Text; using IO.Swagger.Client; namespace IO.Swagger.Client { + /// + /// Represents a set of configuration settings + /// public class Configuration{ + + /// + /// Gets or sets the API client. This is the default API client for making HTTP calls. + /// + /// The API client. public static ApiClient apiClient = new ApiClient(); + /// + /// Gets or sets the username (HTTP basic authentication) + /// + /// The username. + public static String username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication) + /// + /// The password. + public static String password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name + /// + /// The API key. + public static Dictionary apiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name + /// + /// The prefix of the API key. + public static Dictionary apiKeyPrefix = new Dictionary(); + + } } From 9c747e3e37dea3e2b540c0413e6258a81a1a6731 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 3 Jun 2015 09:21:45 +0800 Subject: [PATCH 4/4] fix query parameters --- .../src/main/resources/csharp/ApiClient.mustache | 14 +++++++++++--- .../src/main/csharp/io/swagger/client/ApiClient.cs | 14 +++++++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index c841efdc1b5a..c5b72977cf5a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -53,7 +53,7 @@ namespace {{invokerPackage}} { // add query parameter, if any foreach(KeyValuePair param in QueryParams) - request.AddUrlSegment(param.Key, param.Value); + request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach(KeyValuePair param in FormParams) @@ -99,13 +99,21 @@ namespace {{invokerPackage}} { } /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// if parameter is DateTime, output in ISO8601 format + /// if parameter is a list of string, join the list with "," + /// otherwise just return the string /// /// The parameter (header, path, query, form) /// Formatted string public string ParameterToString(object obj) { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + if (obj is DateTime) { + return ((DateTime)obj).ToString ("u"); + } else if (obj is List) { + return String.Join(",", obj as List); + } else { + return Convert.ToString (obj); + } } /// diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs index c801bb1a7361..39d59f063f2f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs @@ -53,7 +53,7 @@ namespace IO.Swagger.Client { // add query parameter, if any foreach(KeyValuePair param in QueryParams) - request.AddUrlSegment(param.Key, param.Value); + request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach(KeyValuePair param in FormParams) @@ -99,13 +99,21 @@ namespace IO.Swagger.Client { } /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// if parameter is DateTime, output in ISO8601 format + /// if parameter is a list of string, join the list with "," + /// otherwise just return the string /// /// The parameter (header, path, query, form) /// Formatted string public string ParameterToString(object obj) { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + if (obj is DateTime) { + return ((DateTime)obj).ToString ("u"); + } else if (obj is List) { + return String.Join(",", obj as List); + } else { + return Convert.ToString (obj); + } } ///