From a6012ecf415fb3cc007069d7798a77aca730e337 Mon Sep 17 00:00:00 2001 From: Andrew B Date: Mon, 20 Jul 2015 23:26:59 -0700 Subject: [PATCH] Initial commit of the Unity3D C# .net 2.0 generator --- .../Unity3DCsharpDotNet2ClientCodegen.java | 248 +++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../Unity3DCsharpDotNet2/ApiClient.mustache | 291 ++++++++++++++++++ .../ApiException.mustache | 48 +++ .../Configuration.mustache | 99 ++++++ .../resources/Unity3DCsharpDotNet2/README.md | 13 + .../Unity3DCsharpDotNet2/api.mustache | 127 ++++++++ .../compile-mono.sh.mustache | 12 + .../Unity3DCsharpDotNet2/model.mustache | 52 ++++ .../packages.config.mustache | 5 + 10 files changed, 896 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Unity3DCsharpDotNet2ClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiException.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/Configuration.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/README.md create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/compile-mono.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/packages.config.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Unity3DCsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Unity3DCsharpDotNet2ClientCodegen.java new file mode 100644 index 00000000000..66591eacac2 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Unity3DCsharpDotNet2ClientCodegen.java @@ -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( + 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( + 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(); + 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) + ""; + } + 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); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 29c7ed0f729..bfdc9716b13 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -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 diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiClient.mustache new file mode 100644 index 00000000000..ba4fdcf3c00 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiClient.mustache @@ -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 +{ + /// + /// API client is mainly responible for making the HTTP call to the API backend. + /// + public class ApiClient + { + private readonly Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="{{basePath}}") + { + BasePath = basePath; + RestClient = new RestClient(BasePath); + } + + /// + /// Gets or sets the base path. + /// + /// The base path + public string BasePath { get; set; } + + /// + /// Gets or sets the RestClient. + /// + /// An instance of the RestClient + public RestClient RestClient { get; set; } + + /// + /// Gets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + } + + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Authentication settings. + /// Object + public Object CallApi(String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary 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); + + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap.Add(key, value); + } + + /// + /// Escape string (url-encoded). + /// + /// String to be escaped. + /// Escaped string. + public string EscapeString(string str) + { + return RestSharp.Contrib.HttpUtility.UrlEncode(str); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + 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"); + } + + /// + /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is a list of string, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public string ParameterToString(object obj) + { + if (obj is DateTime) + return ((DateTime)obj).ToString ("u"); + else if (obj is List) + return String.Join(",", obj as List); + else + return Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// HTTP body (e.g. string, JSON). + /// Object type. + /// Object representation of the JSON string. + public object Deserialize(string content, Type type, IList 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); + } + } + + /// + /// Serialize an object into JSON string. + /// + /// Object. + /// JSON string. + public string Serialize(object obj) + { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Get the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + 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; + } + + /// + /// Update parameters based on authentication. + /// + /// Query parameters. + /// Header parameters. + /// Authentication settings. + public void UpdateParamsForAuth(Dictionary queryParams, Dictionary headerParams, string[] authSettings) + { + if (authSettings == null || authSettings.Length == 0) + return; + + foreach (string auth in authSettings) + { + // determine which one to use + switch(auth) + { + {{#authMethods}} + case "{{name}}": + {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + break; + } + } + } + + /// + /// Encode string in base64 format. + /// + /// String to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + + /// + /// Dynamically cast the object into target type. + /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast + /// + /// Object to be casted + /// Target type + /// Casted object + public static Object ConvertType(Object source, Type dest) { + return Convert.ChangeType(source, dest); + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiException.mustache new file mode 100644 index 00000000000..71d0243d729 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/ApiException.mustache @@ -0,0 +1,48 @@ +using System; + +namespace {{packageName}}.Client { + /// + /// API Exception + /// + public class ApiException : Exception { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public Object ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, Object errorContent = null) : base(message) { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/Configuration.mustache new file mode 100644 index 00000000000..67b07069e2f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/Configuration.mustache @@ -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 +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration + { + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "{{packageVersion}}"; + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The API client. + public static ApiClient DefaultApiClient = new ApiClient(); + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public static String Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public static String Password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public static Dictionary ApiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public static Dictionary ApiKeyPrefix = new Dictionary(); + + private static string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + 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; + } + } + + /// + /// Returns a string with essential information for debugging. + /// + 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; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/README.md b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/README.md new file mode 100644 index 00000000000..facbf4d163e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/README.md @@ -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/) + + diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/api.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/api.mustache new file mode 100644 index 00000000000..2e51c913c30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/api.mustache @@ -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}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class {{classname}} : I{{classname}} + { + /// + /// Initializes a new instance of the class. + /// + /// an instance of ApiClient (optional) + /// + public {{classname}}(ApiClient apiClient = null) + { + if (apiClient == null) // use the default one in Configuration + this.ApiClient = Configuration.DefaultApiClient; + else + this.ApiClient = apiClient; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(String basePath) + { + this.ApiClient = new ApiClient(basePath); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + /// The base path + public void SetBasePath(String basePath) + { + this.ApiClient.BasePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + /// The base path + public String GetBasePath(String basePath) + { + return this.ApiClient.BasePath; + } + + /// + /// Gets or sets the API client. + /// + /// An instance of the ApiClient + public ApiClient ApiClient {get; set;} + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + 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(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) 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}} +} diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/compile-mono.sh.mustache new file mode 100644 index 00000000000..499b42a29a5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/compile-mono.sh.mustache @@ -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 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/model.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/model.mustache new file mode 100644 index 00000000000..99da4f8302a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/model.mustache @@ -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 { + + /// + /// {{description}} + /// + [DataContract] + public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} { + {{#vars}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] + public {{{datatype}}} {{name}} { get; set; } + + {{/vars}} + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public {{#parent}} new {{/parent}}string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +{{/model}} +{{/models}} +} diff --git a/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/packages.config.mustache b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/packages.config.mustache new file mode 100644 index 00000000000..7b9cf186303 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Unity3DCsharpDotNet2/packages.config.mustache @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file