fix comment and use 4-space indentation

This commit is contained in:
wing328 2015-07-03 11:45:31 +08:00
parent 57b54d8ad7
commit d7d6ba957e
9 changed files with 2931 additions and 2723 deletions

289
; Normal file
View File

@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
namespace {{packageName}}.Client {
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
public class ApiClient {
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath="{{basePath}}") {
this.BasePath = basePath;
this.RestClient = new RestClient(this.BasePath);
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string BasePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient RestClient { get; set; }
private Dictionary<String, String> DefaultHeaderMap = new Dictionary<String, String>();
public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.DefaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, FileParameter> param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) {
request.AddParameter("application/json", postBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await RestClient.ExecuteTaskAsync(request);
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
DefaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return DefaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// Create FileParameter based on Stream
/// </summary>
/// <param name="name"> parameter name</param>
/// <param name="stream">Stream</param>
/// <returns>FileParameter</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream) {
return FileParameter.Create(name, StreamToByteArray(stream), ((FileStream)stream).Name);
} else {
return FileParameter.Create(name, StreamToByteArray(stream), "temp_name_here");
}
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="content"> HTTP body (e.g. string, JSON)
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type, IList<Parameter> headers=null) {
if (type.GetType() == typeof(Object)) { // return an object
return (Object)content;
} else if (type.Name == "Stream") {
String fileName, filePath;
if (String.IsNullOrEmpty (Configuration.TempFolderPath)) {
filePath = System.IO.Path.GetTempPath ();
} else {
filePath = Configuration.TempFolderPath;
}
Regex regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
Match match = regex.Match(headers.ToString());
if (match.Success) {
// replace first and last " or ', if found
fileName = filePath + match.Value.Replace("\"", "").Replace("'","");
} else {
fileName = filePath + Guid.NewGuid().ToString();
}
File.WriteAllText (fileName, content);
return new FileStream(fileName, FileMode.Open);
} else if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) { // return a datetime object
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
} else if (type.Name == "String" || type.Name.StartsWith("System.Nullable")) { // return primitive
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> 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;
}
}
}
/// <summary>
/// convert a stream to byte array (byte[])
/// Ref: http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
/// </summary>
/// <param name="input">input stream</param>
/// <return>Array of Byte</return>
public byte[] StreamToByteArray(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="dynamic">Object to be casted</param>
/// <param name="dest">Target type</param>
public static dynamic ConvertType(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
}
}

View File

@ -10,279 +10,280 @@ using Newtonsoft.Json;
using RestSharp; using RestSharp;
namespace {{packageName}}.Client { namespace {{packageName}}.Client {
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
public class ApiClient {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class. /// API client is mainly responible for making the HTTP call to the API backend
/// </summary> /// </summary>
/// <param name="basePath">The base path.</param> public class ApiClient {
public ApiClient(String basePath="{{basePath}}") {
this.BasePath = basePath;
this.RestClient = new RestClient(this.BasePath);
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string BasePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient RestClient { get; set; }
private Dictionary<String, String> DefaultHeaderMap = new Dictionary<String, String>();
public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.DefaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, FileParameter> param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) {
request.AddParameter("application/json", postBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await RestClient.ExecuteTaskAsync(request);
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
DefaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return DefaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// Create FileParameter based on Stream
/// </summary>
/// <param name="name"> parameter name</param>
/// <param name="stream">Stream</param>
/// <returns>FileParameter</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream) {
return FileParameter.Create(name, StreamToByteArray(stream), ((FileStream)stream).Name);
} else {
return FileParameter.Create(name, StreamToByteArray(stream), "temp_name_here");
}
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="content"> HTTP body (e.g. string, JSON)
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type, IList<Parameter> headers=null) {
if (type.GetType() == typeof(Object)) { // return an object
return (Object)content;
} else if (type.Name == "Stream") {
String fileName, filePath;
if (String.IsNullOrEmpty (Configuration.TempFolderPath)) {
filePath = System.IO.Path.GetTempPath ();
} else {
filePath = Configuration.TempFolderPath;
}
Regex regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
Match match = regex.Match(headers.ToString());
if (match.Success) {
// replace first and last " or ', if found
fileName = filePath + match.Value.Replace("\"", "").Replace("'","");
} else {
fileName = filePath + Guid.NewGuid().ToString();
}
File.WriteAllText (fileName, content);
return new FileStream(fileName, FileMode.Open);
} else if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) { // return a datetime object
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
} else if (type.Name == "String" || type.Name.StartsWith("System.Nullable")) { // return primitive
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> headerParams, string[] authSettings) {
if (authSettings == null || authSettings.Length == 0)
return;
foreach (string auth in authSettings) { /// <summary>
// determine which one to use /// Initializes a new instance of the <see cref="ApiClient"/> class.
switch(auth) { /// </summary>
{{#authMethods}} /// <param name="basePath">The base path.</param>
case "{{name}}": public ApiClient(String basePath="{{basePath}}") {
{{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}} this.BasePath = basePath;
{{#isOAuth}}//TODO support oauth{{/isOAuth}} this.RestClient = new RestClient(this.BasePath);
break;
{{/authMethods}}
default:
//TODO show warning about security definition not found
break;
} }
}
/// <summary>
} /// Gets or sets the base path.
/// </summary>
/// <summary> /// <value>The base path.</value>
/// convert a stream to byte array (byte[]) public string BasePath { get; set; }
/// Ref: http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
/// </summary> /// <summary>
/// <param name="input">input stream</param> /// Gets or sets the RestClient
/// <return>Array of Byte</return> /// </summary>
public byte[] StreamToByteArray(Stream input) /// <value>The RestClient.</value>
{ public RestClient RestClient { get; set; }
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream()) private Dictionary<String, String> DefaultHeaderMap = new Dictionary<String, String>();
{
int read; public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
while ((read = input.Read(buffer, 0, buffer.Length)) > 0) Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
{ Dictionary<String, FileParameter> fileParams, String[] authSettings) {
ms.Write(buffer, 0, read); var response = Task.Run(async () => {
var resp = await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.DefaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, FileParameter> param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) {
request.AddParameter("application/json", postBody, ParameterType.RequestBody); // http body (model) parameter
} }
return ms.ToArray();
return (Object) await RestClient.ExecuteTaskAsync(request);
} }
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name </param>
/// <param name="value"> Header field value </param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
DefaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return DefaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str">String to be escaped</param>
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// Create FileParameter based on Stream
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="stream">Input stream</param>
/// <returns>FileParameter</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream) {
return FileParameter.Create(name, StreamToByteArray(stream), ((FileStream)stream).Name);
} else {
return FileParameter.Create(name, StreamToByteArray(stream), "temp_name_here");
}
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj">The parameter (header, path, query, form)</param>
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="content">HTTP body (e.g. string, JSON)</param>
/// <param name="type">Object type</param>
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type, IList<Parameter> headers=null) {
if (type.GetType() == typeof(Object)) { // return an object
return (Object)content;
} else if (type.Name == "Stream") {
String fileName, filePath;
if (String.IsNullOrEmpty (Configuration.TempFolderPath)) {
filePath = System.IO.Path.GetTempPath ();
} else {
filePath = Configuration.TempFolderPath;
}
Regex regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
Match match = regex.Match(headers.ToString());
if (match.Success) {
// replace first and last " or ', if found
fileName = filePath + match.Value.Replace("\"", "").Replace("'","");
} else {
fileName = filePath + Guid.NewGuid().ToString();
}
File.WriteAllText (fileName, content);
return new FileStream(fileName, FileMode.Open);
} else if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) { // return a datetime object
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
} else if (type.Name == "String" || type.Name.StartsWith("System.Nullable")) { // return primitive
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj">Object</param>
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj">Object</param>
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> 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;
}
}
}
/// <summary>
/// convert a stream to byte array (byte[])
/// Ref: http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
/// </summary>
/// <param name="input">input stream</param>
/// <return>Array of Byte</return>
public byte[] StreamToByteArray(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="dynamic">Object to be casted</param>
/// <param name="dest">Target type</param>
public static dynamic ConvertType(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
} }
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="dynamic">Object to be casted</param>
/// <param name="dest">Target type</param>
public static dynamic ConvertType(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
}
} }

View File

@ -8,165 +8,162 @@ using {{packageName}}.Client;
{{/hasImport}} {{/hasImport}}
namespace {{packageName}}.Api { namespace {{packageName}}.Api {
{{#operations}} {{#operations}}
public interface I{{classname}} { public interface I{{classname}} {
{{#operation}} {{#operation}}
/// <summary> /// <summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> /// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param> {{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
{{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>{{/returnType}} {{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
/// <summary> /// <summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> /// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param> {{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
{{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>{{/returnType}} {{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>
{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}} {{/operation}}
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class {{classname}} : I{{classname}} {
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public {{classname}}(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
} else {
this.ApiClient = apiClient;
}
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class. /// Represents a collection of functions to interact with the API endpoints
/// </summary> /// </summary>
/// <returns></returns> public class {{classname}} : I{{classname}} {
public {{classname}}(String basePath)
{ /// <summary>
this.ApiClient = new ApiClient(basePath); /// Initializes a new instance of the <see cref="{{classname}}"/> class.
} /// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <summary> /// <returns></returns>
/// Sets the base path of the API client. public {{classname}}(ApiClient apiClient = null) {
/// </summary> if (apiClient == null) { // use the default one in Configuration
/// <value>The base path</value> this.ApiClient = Configuration.DefaultApiClient;
public void SetBasePath(String basePath) { } else {
this.ApiClient.BasePath = basePath; this.ApiClient = apiClient;
} }
}
/// <summary>
/// Gets the base path of the API client. /// <summary>
/// </summary> /// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// <value>The base path</value> /// </summary>
public String GetBasePath(String basePath) { /// <returns></returns>
return this.ApiClient.BasePath; public {{classname}}(String basePath)
} {
this.ApiClient = new ApiClient(basePath);
/// <summary> }
/// Gets or sets the API client.
/// </summary> /// <summary>
/// <value>The API client</value> /// Sets the base path of the API client.
public ApiClient ApiClient {get; set;} /// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
{{#operation}} this.ApiClient.BasePath = basePath;
/// <summary> }
/// {{summary}} {{notes}}
/// </summary> /// <summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param> /// Gets the base path of the API client.
{{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>{{/returnType}} /// </summary>
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { /// <value>The base path</value>
public String GetBasePath(String basePath) {
{{#allParams}}{{#required}} return this.ApiClient.BasePath;
// verify the required parameter '{{paramName}}' is set }
if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
{{/required}}{{/allParams}} /// <summary>
/// Gets or sets the API client.
var path = "{{path}}"; /// </summary>
path = path.Replace("{format}", "json"); /// <value>The API client</value>
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}})); public ApiClient ApiClient {get; set;}
{{/pathParams}}
{{#operation}}
var queryParams = new Dictionary<String, String>(); /// <summary>
var headerParams = new Dictionary<String, String>(); /// {{summary}} {{notes}}
var formParams = new Dictionary<String, String>(); /// </summary>
var fileParams = new Dictionary<String, FileParameter>(); {{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
String postBody = null; {{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>
public {{{returnType}}}{{/returnType}}{{^returnType}}public void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter
{{/queryParams}} {{#allParams}}{{#required}}
{{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter // verify the required parameter '{{paramName}}' is set
{{/headerParams}} if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
{{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/required}}{{/allParams}}
{{/formParams}}
{{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter var path = "{{path}}";
{{/bodyParam}} path = path.Replace("{format}", "json");
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}}));
// authentication setting, if any {{/pathParams}}
String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
var queryParams = new Dictionary<String, String>();
// make the HTTP request var headerParams = new Dictionary<String, String>();
IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
if (((int)response.StatusCode) >= 400) { String postBody = null;
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content);
} {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter
{{/queryParams}}
{{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}return;{{/returnType}} {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter
} {{/headerParams}}
{{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}}
/// <summary> {{/formParams}}
/// {{summary}} {{notes}} {{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter
/// </summary> {{/bodyParam}}
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
{{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>{{/returnType}} // authentication setting, if any
public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
{{#allParams}}{{#required}} // make the HTTP request
// verify the required parameter '{{paramName}}' is set IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
{{/required}}{{/allParams}} if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content);
var path = "{{path}}"; }
path = path.Replace("{format}", "json");
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}})); {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}return;{{/returnType}}
{{/pathParams}} }
var queryParams = new Dictionary<String, String>(); /// <summary>
var headerParams = new Dictionary<String, String>(); /// {{summary}} {{notes}}
var formParams = new Dictionary<String, String>(); /// </summary>
var fileParams = new Dictionary<String, FileParameter>(); {{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
String postBody = null; {{/allParams}}{{#returnType}}/// <returns>{{{returnType}}}</returns>
public async Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set
{{/queryParams}} if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
{{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter {{/required}}{{/allParams}}
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} var path = "{{path}}";
{{/formParams}} path = path.Replace("{format}", "json");
{{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}}));
{{/bodyParam}} {{/pathParams}}
// authentication setting, if any var queryParams = new Dictionary<String, String>();
String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
// make the HTTP request var fileParams = new Dictionary<String, FileParameter>();
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); String postBody = null;
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter
} {{/queryParams}}
{{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}} {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter
return;{{/returnType}} {{/headerParams}}
} {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}}
{{/operation}} {{/formParams}}
} {{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter
{{/operations}} {{/bodyParam}}
// authentication setting, if any
String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
{{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}
return;{{/returnType}}
}
{{/operation}}
}
{{/operations}}
} }

View File

@ -7,421 +7,410 @@ using IO.Swagger.Client;
using IO.Swagger.Model; using IO.Swagger.Model;
namespace IO.Swagger.Api { namespace IO.Swagger.Api {
public interface IStoreApi {
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
Dictionary<String, int?> GetInventory ();
public interface IStoreApi { /// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// <summary> /// </summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// <returns>Dictionary<String, int?></returns>
/// </summary> Task<Dictionary<String, int?>> GetInventoryAsync ();
/// <returns>Dictionary<String, int?></returns>
Dictionary<String, int?> GetInventory (); /// <summary>
/// Place an order for a pet
/// <summary> /// </summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// <param name="body">order placed for purchasing the pet</param>
/// </summary> /// <returns>Order</returns>
/// <returns>Dictionary<String, int?></returns> Order PlaceOrder (Order body);
Task<Dictionary<String, int?>> GetInventoryAsync ();
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
Order PlaceOrder (Order body);
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
Task<Order> PlaceOrderAsync (Order body);
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
Order GetOrderById (string orderId);
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
Task<Order> GetOrderByIdAsync (string orderId);
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
void DeleteOrder (string orderId);
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
Task DeleteOrderAsync (string orderId);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class StoreApi : IStoreApi {
/// <summary>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
} else {
this.ApiClient = apiClient;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <returns></returns>
public StoreApi(String basePath)
{
this.ApiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.ApiClient.BasePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.ApiClient.BasePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient ApiClient {get; set;}
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content);
}
return (Dictionary<String, int?>) ApiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>), response.Headers);
}
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public async Task<Dictionary<String, int?>> GetInventoryAsync () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Dictionary<String, int?>) ApiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>), response.Headers);
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public Order PlaceOrder (Order body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public async Task<Order> PlaceOrderAsync (Order body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
postBody = ApiClient.Serialize(body); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
public Order GetOrderById (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
public async Task<Order> GetOrderByIdAsync (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
public void DeleteOrder (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content);
}
return;
}
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
public async Task DeleteOrderAsync (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
Task<Order> PlaceOrderAsync (Order body);
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
Order GetOrderById (string orderId);
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
Task<Order> GetOrderByIdAsync (string orderId);
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
void DeleteOrder (string orderId);
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
Task DeleteOrderAsync (string orderId);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class StoreApi : IStoreApi {
/// <summary>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
} else {
this.ApiClient = apiClient;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <returns></returns>
public StoreApi(String basePath)
{
this.ApiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.ApiClient.BasePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.ApiClient.BasePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient ApiClient {get; set;}
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content);
}
return (Dictionary<String, int?>) ApiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>), response.Headers);
}
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public async Task<Dictionary<String, int?>> GetInventoryAsync () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Dictionary<String, int?>) ApiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>), response.Headers);
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public Order PlaceOrder (Order body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public async Task<Order> PlaceOrderAsync (Order body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
postBody = ApiClient.Serialize(body); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
public Order GetOrderById (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
/// <param name="orderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
public async Task<Order> GetOrderByIdAsync (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers);
}
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
public void DeleteOrder (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// 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, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content);
}
return;
}
/// <summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary>
/// <param name="orderId">ID of the order that needs to be deleted</param>
public async Task DeleteOrderAsync (string orderId) {
// verify the required parameter 'orderId' is set
if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId));
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(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, response.Content);
}
return;
}
}
} }

View File

@ -10,284 +10,285 @@ using Newtonsoft.Json;
using RestSharp; using RestSharp;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
public class ApiClient {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class. /// API client is mainly responible for making the HTTP call to the API backend
/// </summary> /// </summary>
/// <param name="basePath">The base path.</param> public class ApiClient {
public ApiClient(String basePath="http://petstore.swagger.io/v2") {
this.BasePath = basePath;
this.RestClient = new RestClient(this.BasePath);
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string BasePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient RestClient { get; set; }
private Dictionary<String, String> DefaultHeaderMap = new Dictionary<String, String>();
public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.DefaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, FileParameter> param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) {
request.AddParameter("application/json", postBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await RestClient.ExecuteTaskAsync(request);
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
DefaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return DefaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// Create FileParameter based on Stream
/// </summary>
/// <param name="name"> parameter name</param>
/// <param name="stream">Stream</param>
/// <returns>FileParameter</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream) {
return FileParameter.Create(name, StreamToByteArray(stream), ((FileStream)stream).Name);
} else {
return FileParameter.Create(name, StreamToByteArray(stream), "temp_name_here");
}
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="content"> HTTP body (e.g. string, JSON)
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type, IList<Parameter> headers=null) {
if (type.GetType() == typeof(Object)) { // return an object
return (Object)content;
} else if (type.Name == "Stream") {
String fileName, filePath;
if (String.IsNullOrEmpty (Configuration.TempFolderPath)) {
filePath = System.IO.Path.GetTempPath ();
} else {
filePath = Configuration.TempFolderPath;
}
Regex regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
Match match = regex.Match(headers.ToString());
if (match.Success) {
// replace first and last " or ', if found
fileName = filePath + match.Value.Replace("\"", "").Replace("'","");
} else {
fileName = filePath + Guid.NewGuid().ToString();
}
File.WriteAllText (fileName, content);
return new FileStream(fileName, FileMode.Open);
} else if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) { // return a datetime object
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
} else if (type.Name == "String" || type.Name.StartsWith("System.Nullable")) { // return primitive
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> headerParams, string[] authSettings) {
if (authSettings == null || authSettings.Length == 0)
return;
foreach (string auth in authSettings) { /// <summary>
// determine which one to use /// Initializes a new instance of the <see cref="ApiClient"/> class.
switch(auth) { /// </summary>
/// <param name="basePath">The base path.</param>
case "api_key": public ApiClient(String basePath="http://petstore.swagger.io/v2") {
headerParams["api_key"] = GetApiKeyWithPrefix("api_key"); this.BasePath = basePath;
this.RestClient = new RestClient(this.BasePath);
break;
case "petstore_auth":
//TODO support oauth
break;
default:
//TODO show warning about security definition not found
break;
} }
}
/// <summary>
} /// Gets or sets the base path.
/// </summary>
/// <summary> /// <value>The base path.</value>
/// convert a stream to byte array (byte[]) public string BasePath { get; set; }
/// Ref: http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
/// </summary> /// <summary>
/// <param name="input">input stream</param> /// Gets or sets the RestClient
/// <return>Array of Byte</return> /// </summary>
public byte[] StreamToByteArray(Stream input) /// <value>The RestClient.</value>
{ public RestClient RestClient { get; set; }
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream()) private Dictionary<String, String> DefaultHeaderMap = new Dictionary<String, String>();
{
int read; public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
while ((read = input.Read(buffer, 0, buffer.Length)) > 0) Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
{ Dictionary<String, FileParameter> fileParams, String[] authSettings) {
ms.Write(buffer, 0, read); var response = Task.Run(async () => {
var resp = await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, String[] authSettings) {
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.DefaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, FileParameter> param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) {
request.AddParameter("application/json", postBody, ParameterType.RequestBody); // http body (model) parameter
} }
return ms.ToArray();
return (Object) await RestClient.ExecuteTaskAsync(request);
} }
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name </param>
/// <param name="value"> Header field value </param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
DefaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return DefaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str">String to be escaped</param>
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// Create FileParameter based on Stream
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="stream">Input stream</param>
/// <returns>FileParameter</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream) {
return FileParameter.Create(name, StreamToByteArray(stream), ((FileStream)stream).Name);
} else {
return FileParameter.Create(name, StreamToByteArray(stream), "temp_name_here");
}
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj">The parameter (header, path, query, form)</param>
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="content">HTTP body (e.g. string, JSON)</param>
/// <param name="type">Object type</param>
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type, IList<Parameter> headers=null) {
if (type.GetType() == typeof(Object)) { // return an object
return (Object)content;
} else if (type.Name == "Stream") {
String fileName, filePath;
if (String.IsNullOrEmpty (Configuration.TempFolderPath)) {
filePath = System.IO.Path.GetTempPath ();
} else {
filePath = Configuration.TempFolderPath;
}
Regex regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
Match match = regex.Match(headers.ToString());
if (match.Success) {
// replace first and last " or ', if found
fileName = filePath + match.Value.Replace("\"", "").Replace("'","");
} else {
fileName = filePath + Guid.NewGuid().ToString();
}
File.WriteAllText (fileName, content);
return new FileStream(fileName, FileMode.Open);
} else if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) { // return a datetime object
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
} else if (type.Name == "String" || type.Name.StartsWith("System.Nullable")) { // return primitive
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj">Object</param>
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj">Object</param>
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> 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;
}
}
}
/// <summary>
/// convert a stream to byte array (byte[])
/// Ref: http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
/// </summary>
/// <param name="input">input stream</param>
/// <return>Array of Byte</return>
public byte[] StreamToByteArray(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="dynamic">Object to be casted</param>
/// <param name="dest">Target type</param>
public static dynamic ConvertType(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
} }
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="dynamic">Object to be casted</param>
/// <param name="dest">Target type</param>
public static dynamic ConvertType(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
}
} }