Skip to content

[C#] Added ApiClient (Pluggable) and authentication (API key and HTTP basic auth) #808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 5, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ public CSharpClientCodegen() {

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"));
Expand Down
207 changes: 207 additions & 0 deletions modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;

namespace {{invokerPackage}} {
/// <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, String> 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, string> param in FileParams)
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);

}

/// <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>
/// 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="json"> JSON string
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;

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 apiKey)
{
var apiKeyValue = "";
Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.apiKeyPrefix.TryGetValue (apiKey, 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>
/// 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);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using {{invokerPackage}};

namespace {{invokerPackage}} {
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration{

/// <summary>
/// Gets or sets the API client. This is the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public static ApiClient apiClient = new ApiClient();

/// <summary>
/// Gets or sets the username (HTTP basic authentication)
/// </summary>
/// <value>The username.</value>
public static String username { get; set; }

/// <summary>
/// Gets or sets the password (HTTP basic authentication)
/// </summary>
/// <value>The password.</value>
public static String password { get; set; }

/// <summary>
/// Gets or sets the API key based on the authentication name
/// </summary>
/// <value>The API key.</value>
public static Dictionary<String, String> apiKey = new Dictionary<String, String>();

/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name
/// </summary>
/// <value>The prefix of the API key.</value>
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>();


}
}
Loading