forked from loafle/openapi-generator-original
Initial commit of the Unity3D C# .net 2.0 generator
This commit is contained in:
parent
e879268043
commit
a6012ecf41
@ -0,0 +1,248 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.codegen.CliOption;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class Unity3DCsharpDotNet2ClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String packageName = "IO.Swagger";
|
||||
protected String packageVersion = "1.0.0";
|
||||
protected String clientPackage = "IO.Swagger.Client";
|
||||
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "Unity3DCsharpDotNet2";
|
||||
|
||||
public Unity3DCsharpDotNet2ClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code" + File.separator + "Unity3DCsharpDotNet2";
|
||||
modelTemplateFiles.put("model.mustache", ".cs");
|
||||
apiTemplateFiles.put("api.mustache", ".cs");
|
||||
templateDir = "Unity3DCsharpDotNet2";
|
||||
apiPackage = "IO.Swagger.Api";
|
||||
modelPackage = "IO.Swagger.Model";
|
||||
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while")
|
||||
);
|
||||
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"string",
|
||||
"bool?",
|
||||
"double?",
|
||||
"int?",
|
||||
"long?",
|
||||
"float?",
|
||||
"byte[]",
|
||||
"List",
|
||||
"Dictionary",
|
||||
"DateTime?",
|
||||
"String",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float",
|
||||
"Stream", // not really a primitive, we include it to avoid model import
|
||||
"Object")
|
||||
);
|
||||
instantiationTypes.put("array", "List");
|
||||
instantiationTypes.put("map", "Dictionary");
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("string", "string");
|
||||
typeMapping.put("boolean", "bool?");
|
||||
typeMapping.put("integer", "int?");
|
||||
typeMapping.put("float", "float?");
|
||||
typeMapping.put("long", "long?");
|
||||
typeMapping.put("double", "double?");
|
||||
typeMapping.put("number", "double?");
|
||||
typeMapping.put("datetime", "DateTime?");
|
||||
typeMapping.put("date", "DateTime?");
|
||||
typeMapping.put("file", "Stream");
|
||||
typeMapping.put("array", "List");
|
||||
typeMapping.put("list", "List");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
typeMapping.put("object", "Object");
|
||||
|
||||
cliOptions.clear();
|
||||
cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger"));
|
||||
cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0"));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if (additionalProperties.containsKey("packageVersion")) {
|
||||
packageVersion = (String) additionalProperties.get("packageVersion");
|
||||
} else {
|
||||
additionalProperties.put("packageVersion", packageVersion);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey("packageName")) {
|
||||
packageName = (String) additionalProperties.get("packageName");
|
||||
apiPackage = packageName + ".Api";
|
||||
modelPackage = packageName + ".Model";
|
||||
clientPackage = packageName + ".Client";
|
||||
} else {
|
||||
additionalProperties.put("packageName", packageName);
|
||||
}
|
||||
|
||||
additionalProperties.put("clientPackage", clientPackage);
|
||||
|
||||
supportingFiles.add(new SupportingFile("Configuration.mustache",
|
||||
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs"));
|
||||
supportingFiles.add(new SupportingFile("ApiClient.mustache",
|
||||
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs"));
|
||||
supportingFiles.add(new SupportingFile("ApiException.mustache",
|
||||
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs"));
|
||||
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
|
||||
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
|
||||
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "Unity3DCsharpDotNet2";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Unity3D-Csharp-DotNet2 client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize the variable name
|
||||
// pet_id => PetId
|
||||
name = camelize(name);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toParamName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize(lower) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
return camelize(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
// should be the same as the model name
|
||||
return toModelName(name);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
||||
type = typeMapping.get(swaggerType.toLowerCase());
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId);
|
||||
}
|
||||
|
||||
}
|
@ -26,3 +26,4 @@ io.swagger.codegen.languages.TizenClientCodegen
|
||||
io.swagger.codegen.languages.TypeScriptAngularClientCodegen
|
||||
io.swagger.codegen.languages.TypeScriptNodeClientCodegen
|
||||
io.swagger.codegen.languages.AkkaScalaClientCodegen
|
||||
io.swagger.codegen.languages.Unity3DCsharpDotNet2ClientCodegen
|
||||
|
@ -0,0 +1,291 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.IO;
|
||||
using System.Web;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using RestSharp;
|
||||
using RestSharp.Extensions;
|
||||
|
||||
namespace {{packageName}}.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// API client is mainly responible for making the HTTP call to the API backend.
|
||||
/// </summary>
|
||||
public class ApiClient
|
||||
{
|
||||
private readonly Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiClient" /> class.
|
||||
/// </summary>
|
||||
/// <param name="basePath">The base path.</param>
|
||||
public ApiClient(String basePath="{{basePath}}")
|
||||
{
|
||||
BasePath = basePath;
|
||||
RestClient = new RestClient(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>An instance of the RestClient</value>
|
||||
public RestClient RestClient { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default header.
|
||||
/// </summary>
|
||||
public Dictionary<String, String> DefaultHeader
|
||||
{
|
||||
get { return _defaultHeaderMap; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the HTTP request (Sync).
|
||||
/// </summary>
|
||||
/// <param name="path">URL path.</param>
|
||||
/// <param name="method">HTTP method.</param>
|
||||
/// <param name="queryParams">Query parameters.</param>
|
||||
/// <param name="postBody">HTTP body (POST request).</param>
|
||||
/// <param name="headerParams">Header parameters.</param>
|
||||
/// <param name="formParams">Form parameters.</param>
|
||||
/// <param name="fileParams">File parameters.</param>
|
||||
/// <param name="authSettings">Authentication settings.</param>
|
||||
/// <returns>Object</returns>
|
||||
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 request = new RestRequest(path, method);
|
||||
|
||||
UpdateParamsForAuth(queryParams, headerParams, authSettings);
|
||||
|
||||
// add default header, if any
|
||||
foreach(var defaultHeader in _defaultHeaderMap)
|
||||
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
|
||||
|
||||
// add header parameter, if any
|
||||
foreach(var param in headerParams)
|
||||
request.AddHeader(param.Key, param.Value);
|
||||
|
||||
// add query parameter, if any
|
||||
foreach(var param in queryParams)
|
||||
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
|
||||
|
||||
// add form parameter, if any
|
||||
foreach(var param in formParams)
|
||||
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
|
||||
|
||||
// add file parameter, if any
|
||||
foreach(var param in fileParams)
|
||||
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
|
||||
|
||||
if (postBody != null) // http body (model) parameter
|
||||
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
|
||||
|
||||
return (Object)RestClient.Execute(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>
|
||||
/// Escape string (url-encoded).
|
||||
/// </summary>
|
||||
/// <param name="str">String to be escaped.</param>
|
||||
/// <returns>Escaped string.</returns>
|
||||
public string EscapeString(string str)
|
||||
{
|
||||
return RestSharp.Contrib.HttpUtility.UrlEncode(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, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name));
|
||||
else
|
||||
return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided");
|
||||
}
|
||||
|
||||
/// <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 == typeof(Object)) // return an object
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
if (type == typeof(Stream))
|
||||
{
|
||||
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
|
||||
? Path.GetTempPath()
|
||||
: Configuration.TempFolderPath;
|
||||
|
||||
var fileName = filePath + Guid.NewGuid();
|
||||
if (headers != null)
|
||||
{
|
||||
var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
|
||||
var match = regex.Match(headers.ToString());
|
||||
if (match.Success)
|
||||
fileName = filePath + match.Value.Replace("\"", "").Replace("'", "");
|
||||
}
|
||||
File.WriteAllText(fileName, content);
|
||||
return new FileStream(fileName, FileMode.Open);
|
||||
|
||||
}
|
||||
|
||||
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
|
||||
{
|
||||
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
|
||||
}
|
||||
|
||||
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
|
||||
{
|
||||
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="apiKeyIdentifier">API key identifier (authentication scheme).</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>
|
||||
/// Encode string in base64 format.
|
||||
/// </summary>
|
||||
/// <param name="text">String to be encoded.</param>
|
||||
/// <returns>Encoded string.</returns>
|
||||
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="source">Object to be casted</param>
|
||||
/// <param name="dest">Target type</param>
|
||||
/// <returns>Casted object</returns>
|
||||
public static Object ConvertType(Object source, Type dest) {
|
||||
return Convert.ChangeType(source, dest);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
using System;
|
||||
|
||||
namespace {{packageName}}.Client {
|
||||
/// <summary>
|
||||
/// API Exception
|
||||
/// </summary>
|
||||
public class ApiException : Exception {
|
||||
/// <summary>
|
||||
/// Gets or sets the error code (HTTP status code)
|
||||
/// </summary>
|
||||
/// <value>The error code (HTTP status code).</value>
|
||||
public int ErrorCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error content (body json object)
|
||||
/// </summary>
|
||||
/// <value>The error content (Http response body).</value>
|
||||
public Object ErrorContent { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="basePath">The base path.</param>
|
||||
public ApiException() {}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="errorCode">HTTP status code.</param>
|
||||
/// <param name="message">Error message.</param>
|
||||
public ApiException(int errorCode, string message) : base(message) {
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="errorCode">HTTP status code.</param>
|
||||
/// <param name="message">Error message.</param>
|
||||
/// <param name="errorContent">Error content.</param>
|
||||
public ApiException(int errorCode, string message, Object errorContent = null) : base(message) {
|
||||
this.ErrorCode = errorCode;
|
||||
this.ErrorContent = errorContent;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace {{packageName}}.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a set of configuration settings
|
||||
/// </summary>
|
||||
public class Configuration
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Version of the package.
|
||||
/// </summary>
|
||||
/// <value>Version of the package.</value>
|
||||
public const string Version = "{{packageVersion}}";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the default API client for making HTTP calls.
|
||||
/// </summary>
|
||||
/// <value>The API client.</value>
|
||||
public static ApiClient DefaultApiClient = 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>();
|
||||
|
||||
private static string _tempFolderPath = Path.GetTempPath();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the temporary folder path to store the files downloaded from the server.
|
||||
/// </summary>
|
||||
/// <value>Folder path.</value>
|
||||
public static String TempFolderPath
|
||||
{
|
||||
get { return _tempFolderPath; }
|
||||
|
||||
set
|
||||
{
|
||||
if (String.IsNullOrEmpty(value))
|
||||
{
|
||||
_tempFolderPath = value;
|
||||
return;
|
||||
}
|
||||
|
||||
// create the directory if it does not exist
|
||||
if (!Directory.Exists(value))
|
||||
Directory.CreateDirectory(value);
|
||||
|
||||
// check if the path contains directory separator at the end
|
||||
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
|
||||
_tempFolderPath = value;
|
||||
else
|
||||
_tempFolderPath = value + Path.DirectorySeparatorChar;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a string with essential information for debugging.
|
||||
/// </summary>
|
||||
public static String ToDebugReport()
|
||||
{
|
||||
String report = "C# SDK ({{packageName}}) Debug Report:\n";
|
||||
report += " OS: " + Environment.OSVersion + "\n";
|
||||
report += " .NET Framework Version: " + Assembly
|
||||
.GetExecutingAssembly()
|
||||
.GetReferencedAssemblies()
|
||||
.Where(x => x.Name == "System.Core").First().Version.ToString() + "\n";
|
||||
report += " Version of the API: {{version}}\n";
|
||||
report += " SDK Package Version: {{packageVersion}}\n";
|
||||
|
||||
return report;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
# Unity3D-Csharp-DotNet2
|
||||
|
||||
This generator creates managed libraries for use in games created using the Unity3D engine/framework.
|
||||
|
||||
## Frameworks supported
|
||||
- .NET 2.0
|
||||
|
||||
## Dependencies
|
||||
- NuGet packages:
|
||||
-- [RestSharp] (https://www.nuget.org/packages/RestSharp)
|
||||
-- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/)
|
||||
|
||||
|
@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using RestSharp;
|
||||
using {{packageName}}.Client;
|
||||
{{#hasImport}}using {{packageName}}.Model;
|
||||
{{/hasImport}}
|
||||
|
||||
namespace {{packageName}}.Api
|
||||
{
|
||||
{{#operations}}
|
||||
public interface I{{classname}}
|
||||
{
|
||||
{{#operation}}
|
||||
/// <summary>
|
||||
/// {{summary}} {{notes}}
|
||||
/// </summary>
|
||||
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
|
||||
{{/allParams}}/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
|
||||
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{/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>
|
||||
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public {{classname}}(String basePath)
|
||||
{
|
||||
this.ApiClient = new ApiClient(basePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the base path of the API client.
|
||||
/// </summary>
|
||||
/// <param name="basePath">The base path</param>
|
||||
/// <value>The base path</value>
|
||||
public void SetBasePath(String basePath)
|
||||
{
|
||||
this.ApiClient.BasePath = basePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the base path of the API client.
|
||||
/// </summary>
|
||||
/// <param name="basePath">The base path</param>
|
||||
/// <value>The base path</value>
|
||||
public String GetBasePath(String basePath)
|
||||
{
|
||||
return this.ApiClient.BasePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the API client.
|
||||
/// </summary>
|
||||
/// <value>An instance of the ApiClient</param>
|
||||
public ApiClient ApiClient {get; set;}
|
||||
|
||||
{{#operation}}
|
||||
/// <summary>
|
||||
/// {{summary}} {{notes}}
|
||||
/// </summary>
|
||||
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
|
||||
{{/allParams}}/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
|
||||
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
|
||||
{
|
||||
{{#allParams}}{{#required}}
|
||||
// verify the required parameter '{{paramName}}' is set
|
||||
if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
|
||||
{{/required}}{{/allParams}}
|
||||
|
||||
var path = "{{path}}";
|
||||
path = path.Replace("{format}", "json");
|
||||
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}}));
|
||||
{{/pathParams}}
|
||||
|
||||
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;
|
||||
|
||||
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter
|
||||
{{/queryParams}}
|
||||
{{#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}}
|
||||
{{/formParams}}
|
||||
{{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter
|
||||
{{/bodyParam}}
|
||||
|
||||
// authentication setting, if any
|
||||
String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
|
||||
|
||||
// make the HTTP request
|
||||
IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
|
||||
|
||||
if (((int)response.StatusCode) >= 400)
|
||||
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content);
|
||||
else if (((int)response.StatusCode) == 0)
|
||||
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.ErrorMessage, response.ErrorMessage);
|
||||
|
||||
{{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}return;{{/returnType}}
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
wget -nc https://nuget.org/nuget.exe;
|
||||
mozroots --import --sync
|
||||
mono nuget.exe install vendor/packages.config -o vendor;
|
||||
mkdir -p bin;
|
||||
mcs -r:vendor/Newtonsoft.Json.7.0.1/lib/net20/Newtonsoft.Json.dll,\
|
||||
vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\
|
||||
System.Runtime.Serialization.dll \
|
||||
-target:library \
|
||||
-out:bin/{{clientPackage}}.dll \
|
||||
-recurse:src/*.cs \
|
||||
-doc:bin/{{clientPackage}}.xml \
|
||||
-platform:anycpu
|
@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
namespace {{packageName}}.Model {
|
||||
|
||||
/// <summary>
|
||||
/// {{description}}
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} {
|
||||
{{#vars}}
|
||||
/// <summary>
|
||||
/// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
|
||||
/// </summary>{{#description}}
|
||||
/// <value>{{{description}}}</value>{{/description}}
|
||||
[DataMember(Name="{{baseName}}", EmitDefaultValue=false)]
|
||||
public {{{datatype}}} {{name}} { get; set; }
|
||||
|
||||
{{/vars}}
|
||||
|
||||
/// <summary>
|
||||
/// Get the string presentation of the object
|
||||
/// </summary>
|
||||
/// <returns>String presentation of the object</returns>
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class {{classname}} {\n");
|
||||
{{#vars}}
|
||||
sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
|
||||
{{/vars}}
|
||||
sb.Append("}\n");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the JSON string presentation of the object
|
||||
/// </summary>
|
||||
/// <returns>JSON string presentation of the object</returns>
|
||||
public {{#parent}} new {{/parent}}string ToJson() {
|
||||
return JsonConvert.SerializeObject(this, Formatting.Indented);
|
||||
}
|
||||
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="RestSharp.Net2" version="1.1.11" targetFramework="net20" developmentDependency="true" />
|
||||
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net20" developmentDependency="true" />
|
||||
</packages>
|
Loading…
x
Reference in New Issue
Block a user