diff --git a/generation/templates/AbstractOpenAPISchema.mustache b/generation/templates/AbstractOpenAPISchema.mustache new file mode 100644 index 00000000..05e78204 --- /dev/null +++ b/generation/templates/AbstractOpenAPISchema.mustache @@ -0,0 +1,68 @@ +{{>partial_header}} + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace {{packageName}}.{{modelPackage}} +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + {{>visibility}} abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/generation/templates/ApiClient.mustache b/generation/templates/ApiClient.mustache new file mode 100644 index 00000000..eb5be40d --- /dev/null +++ b/generation/templates/ApiClient.mustache @@ -0,0 +1,842 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^net60OrLater}} +using System.Web; +{{/net60OrLater}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using RestSharp; +using RestSharp.Serializers; +using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} +{{#hasOAuthMethods}} +using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +using {{packageName}}.{{modelPackage}}; + +namespace {{packageName}}.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer + { + private readonly IReadableConfiguration _configuration; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(RestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + FileIO.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); + + public ContentType ContentType { get; set; } = ContentType.Json; + + public DataFormat DataFormat => DataFormat.Json; + } + {{! NOTE: Any changes related to RestSharp should be done in this class. All other client classes are for extensibility by consumers.}} + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + {{>visibility}} partial class ApiClient : ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(RestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(RestRequest request, RestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.Get; + break; + case HttpMethod.Post: + other = RestSharpMethod.Post; + break; + case HttpMethod.Put: + other = RestSharpMethod.Put; + break; + case HttpMethod.Delete: + other = RestSharpMethod.Delete; + break; + case HttpMethod.Head: + other = RestSharpMethod.Head; + break; + case HttpMethod.Options: + other = RestSharpMethod.Options; + break; + case HttpMethod.Patch: + other = RestSharpMethod.Patch; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(path, Method(method)); + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + foreach (var file in fileParam.Value) + { + var bytes = ClientUtils.ReadAsBytes(file); + var fileStream = file as FileStream; + if (fileStream != null) + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); + else + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); + } + } + } + + return request; + } + + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. + private ApiResponse ToApiResponse(RestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies.Cast()) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + {{#hasOAuthMethods}} + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + {{/hasOAuthMethods}} + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + {{#supportsAsync}} + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + { + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + {{/supportsRetry}} + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + }; + return action().Result; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), options, config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), options, config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), options, config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), options, config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), options, config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), options, config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), options, config); + } + #endregion ISynchronousClient + } +} diff --git a/generation/templates/ApiException.mustache b/generation/templates/ApiException.mustache new file mode 100644 index 00000000..f7dadc55 --- /dev/null +++ b/generation/templates/ApiException.mustache @@ -0,0 +1,60 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// API Exception + /// + {{>visibility}} 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; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + 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. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/generation/templates/ApiResponse.mustache b/generation/templates/ApiResponse.mustache new file mode 100644 index 00000000..161c2acd --- /dev/null +++ b/generation/templates/ApiResponse.mustache @@ -0,0 +1,158 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/generation/templates/AssemblyInfo.mustache b/generation/templates/AssemblyInfo.mustache new file mode 100644 index 00000000..d5d937dc --- /dev/null +++ b/generation/templates/AssemblyInfo.mustache @@ -0,0 +1,40 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("{{packageTitle}}")] +[assembly: AssemblyDescription("{{packageDescription}}")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("{{packageCompany}}")] +[assembly: AssemblyProduct("{{packageProductName}}")] +[assembly: AssemblyCopyright("{{packageCopyright}}")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("{{packageVersion}}")] +[assembly: AssemblyFileVersion("{{packageVersion}}")] +{{^supportsAsync}} +// Settings which don't support asynchronous operations rely on non-public constructors +// This is due to how RestSharp requires the type constraint `where T : new()` in places it probably shouldn't. +[assembly: InternalsVisibleTo("RestSharp")] +[assembly: InternalsVisibleTo("NewtonSoft.Json")] +[assembly: InternalsVisibleTo("JsonSubTypes")] +{{/supportsAsync}} diff --git a/generation/templates/ClientUtils.mustache b/generation/templates/ClientUtils.mustache new file mode 100644 index 00000000..5e43c3d0 --- /dev/null +++ b/generation/templates/ClientUtils.mustache @@ -0,0 +1,261 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +{{#useCompareNetObjects}} +using KellermanSoftware.CompareNetObjects; +{{/useCompareNetObjects}} + +namespace {{packageName}}.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + {{#useCompareNetObjects}} + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + {{#equatable}} + ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}(); + comparisonConfig.UseHashCodeIdentifier = true; + {{/equatable}} + compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}}); + } + + {{/useCompareNetObjects}} + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) { + List entries = new List(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry, configuration)); + return string.Join(",", entries); + } + if (obj is Enum && HasEnumMemberAttrValue(obj)) + return GetEnumMemberAttrValue(obj); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Is the Enum decorated with EnumMember Attribute + /// + /// + /// true if found + private static bool HasEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) return true; + return false; + } + + /// + /// Get the EnumMember value + /// + /// + /// EnumMember value as string otherwise null + private static string GetEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) + { + return attr.Value; + } + return null; + } + } +} diff --git a/generation/templates/Configuration.mustache b/generation/templates/Configuration.mustache new file mode 100644 index 00000000..a765ebf1 --- /dev/null +++ b/generation/templates/Configuration.mustache @@ -0,0 +1,730 @@ +{{>partial_header}} + +using System; +{{^net35}} +using System.Collections.Concurrent; +{{/net35}} +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Net.Http; +using System.Net.Security; +{{#useRestSharp}} +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +{{/useRestSharp}} + +namespace {{packageName}}.Client +{ + /// + /// Represents a set of configuration settings + /// + {{>visibility}} class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "{{packageVersion}}"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + {{^netStandard}} + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + {{/netStandard}} + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + private bool _useDefaultCredentials = false; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for accessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + {{#servers.0}} + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + {{/servers.0}} + + /// + /// Gets or sets the operation servers defined in the OpenAPI spec. + /// + /// The operation servers + private IReadOnlyDictionary>> _operationServers; + + {{#hasHttpSignatureMethods}} + + /// + /// HttpSigning configuration + /// + private HttpSigningConfiguration _HttpSigningConfiguration = null; + {{/hasHttpSignatureMethods}} + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = WebUtility.UrlEncode("{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"); + BasePath = "{{{basePath}}}"; + DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKey = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKeyPrefix = new {{^net35}}Concurrent{{/net35}}Dictionary(); + {{#servers}} + {{#-first}} + Servers = new List>() + { + {{/-first}} + { + new Dictionary { + {"url", "{{{url}}}"}, + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {{#variables}} + {{#-first}} + { + "variables", new Dictionary { + {{/-first}} + { + "{{{name}}}", new Dictionary { + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {"default_value", {{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}"{{{defaultValue}}}"}, + {{#enumValues}} + {{#-first}} + { + "enum_values", new List() { + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/enumValues}} + } + }{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/variables}} + } + }{{^-last}},{{/-last}} + {{#-last}} + }; + {{/-last}} + {{/servers}} + OperationServers = new Dictionary>>() + { + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers.0}} + { + "{{{classname}}}.{{{nickname}}}", new List> + { + {{#servers}} + { + new Dictionary + { + {"url", "{{{url}}}"}, + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"} + } + }, + {{/servers}} + } + }, + {{/servers.0}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "{{{basePath}}}") : this() + { + if (string.{{^net35}}IsNullOrWhiteSpace{{/net35}}{{#net35}}IsNullOrEmpty{{/net35}}(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath + { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + public virtual bool UseDefaultCredentials + { + get { return _useDefaultCredentials; } + set { _useDefaultCredentials = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + {{#useRestSharp}} + {{#hasOAuthMethods}} + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + + {{/hasOAuthMethods}} + {{/useRestSharp}} + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + 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; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + {{#servers.0}} + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Gets or sets the operation servers. + /// + /// The operation servers. + public virtual IReadOnlyDictionary>> OperationServers + { + get { return _operationServers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Operation servers may not be null."); + } + _operationServers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(Servers, index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + return GetServerUrl(Servers, index, inputVariables); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index) + { + return GetOperationServerUrl(operation, index, null); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index, Dictionary inputVariables) + { + if (operation != null && OperationServers.TryGetValue(operation, out var operationServer)) + { + return GetServerUrl(operationServer, index, inputVariables); + } + + return null; + } + + /// + /// Returns URL based on server settings. + /// + /// Dictionary of server settings. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + private string GetServerUrl(IList> servers, int index, Dictionary inputVariables) + { + if (index < 0 || index >= servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = servers[index]; + string url = (string)server["url"]; + + if (server.ContainsKey("variables")) + { + // go through each variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use default value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + } + + return url; + } + {{/servers.0}} + {{#hasHttpSignatureMethods}} + + /// + /// Gets and Sets the HttpSigningConfiguration + /// + public HttpSigningConfiguration HttpSigningConfiguration + { + get { return _HttpSigningConfiguration; } + set { _HttpSigningConfiguration = value; } + } + {{/hasHttpSignatureMethods}} + + /// + /// Gets and Sets the RemoteCertificateValidationCallback + /// + public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK ({{{packageName}}}) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: {{{version}}}\n"; + report += " SDK Package Version: {{{packageVersion}}}\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + {{#useRestSharp}} + {{#hasOAuthMethods}} + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, + {{/hasOAuthMethods}} + {{/useRestSharp}} + {{#hasHttpSignatureMethods}} + HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, + {{/hasHttpSignatureMethods}} + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, + ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, + UseDefaultCredentials = second.UseDefaultCredentials, + RemoteCertificateValidationCallback = second.RemoteCertificateValidationCallback ?? first.RemoteCertificateValidationCallback, + }; + return config; + } + #endregion Static Members + } +} diff --git a/generation/templates/ExceptionFactory.mustache b/generation/templates/ExceptionFactory.mustache new file mode 100644 index 00000000..4a141f6f --- /dev/null +++ b/generation/templates/ExceptionFactory.mustache @@ -0,0 +1,14 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + {{>visibility}} delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/generation/templates/GlobalConfiguration.mustache b/generation/templates/GlobalConfiguration.mustache new file mode 100644 index 00000000..93a9ab8a --- /dev/null +++ b/generation/templates/GlobalConfiguration.mustache @@ -0,0 +1,59 @@ +{{>partial_header}} + +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + {{>visibility}} partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} diff --git a/generation/templates/HttpMethod.mustache b/generation/templates/HttpMethod.mustache new file mode 100644 index 00000000..904a042a --- /dev/null +++ b/generation/templates/HttpMethod.mustache @@ -0,0 +1,25 @@ +{{>partial_header}} + +namespace {{packageName}}.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/generation/templates/HttpSigningConfiguration.mustache b/generation/templates/HttpSigningConfiguration.mustache new file mode 100644 index 00000000..9566e1f1 --- /dev/null +++ b/generation/templates/HttpSigningConfiguration.mustache @@ -0,0 +1,803 @@ +{{>partial_header}} + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace {{packageName}}.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + /// + /// Initialize the HashAlgorithm and SigningAlgorithm to default value + /// + public HttpSigningConfiguration() + { + HashAlgorithm = HashAlgorithmName.SHA256; + SigningAlgorithm = "PKCS1-v15"; + } + + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Specify the API key in the form of a string, either configure the KeyString property or configure the KeyFilePath property. + /// + public string KeyString { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validity period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + + /// + /// Gets the Headers for HttpSigning + /// + /// Base path + /// HTTP method + /// Path + /// Request options + /// Http signed headers + public Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) + { + const string HEADER_REQUEST_TARGET = "(request-target)"; + //The time when the HTTP signature expires. The API server should reject HTTP requests + //that have expired. + const string HEADER_EXPIRES = "(expires)"; + //The 'Date' header. + const string HEADER_DATE = "Date"; + //The 'Host' header. + const string HEADER_HOST = "Host"; + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Read the api key from the file + if(File.Exists(KeyFilePath)) + { + this.KeyString = ReadApiKeyFromFile(KeyFilePath); + } + else if(string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); + } + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + var HttpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + { + HttpSigningHeader.Add("(created)"); + } + + if (requestOptions.PathParameters != null) + { + foreach (var pathParam in requestOptions.PathParameters) + { + var tempPath = path.Replace(pathParam.Key, "0"); + path = string.Format(tempPath, pathParam.Value); + } + } + + var httpValues = HttpUtility.ParseQueryString(string.Empty); + foreach (var parameter in requestOptions.QueryParameters) + { +#if (NETCOREAPP) + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value); + } + } + else + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + } +#else + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(parameter.Key + "[]", value); + } + } + else + { + httpValues.Add(parameter.Key, parameter.Value[0]); + } +#endif + } + var uriBuilder = new UriBuilder(string.Concat(basePath, path)); + uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); + + var dateTime = DateTime.Now; + string Digest = string.Empty; + + //get the body + string requestBody = string.Empty; + if (requestOptions.Data != null) + { + var serializerSettings = new JsonSerializerSettings(); + requestBody = JsonConvert.SerializeObject(requestOptions.Data, serializerSettings); + } + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + { + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + } + + foreach (var header in HttpSigningHeader) + { + if (header.Equals(HEADER_REQUEST_TARGET)) + { + var targetUrl = string.Format("{0} {1}{2}", method.ToLower(), uriBuilder.Path, uriBuilder.Query); + HttpSignatureHeader.Add(header.ToLower(), targetUrl); + } + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToUniversalTime().ToString("r"); + HttpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host); + HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host); + } + else if (header.Equals(HEADER_CREATED)) + { + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + } + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest); + HttpSignatureHeader.Add(header.ToLower(), Digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in requestOptions.HeaderParameters) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + if (!isHeaderFound) + { + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + } + + } + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in HttpSignatureHeader) + { + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + } + //Concatenate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm, headerValuesString); + string headerSignatureStr = null; + var keyType = GetKeyType(KeyString); + + if (keyType == PrivateKeyType.RSA) + { + headerSignatureStr = GetRSASignature(signatureStringHash); + } + else if (keyType == PrivateKeyType.ECDSA) + { + headerSignatureStr = GetECDSASignature(signatureStringHash); + } + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (HttpSignatureHeader.ContainsKey(HEADER_CREATED)) + { + authorizationHeaderValue += string.Format(",created={0}", HttpSignatureHeader[HEADER_CREATED]); + } + + if (HttpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + { + authorizationHeaderValue += string.Format(",expires={0}", HttpSignatureHeader[HEADER_EXPIRES]); + } + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", + headersKeysString, headerSignatureStr); + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(HashAlgorithmName hashAlgorithmName, string stringToBeHashed) + { + HashAlgorithm{{nrt?}} hashAlgorithm = null; + + if (hashAlgorithmName == HashAlgorithmName.SHA1) + hashAlgorithm = SHA1.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA256) + hashAlgorithm = SHA256.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA512) + hashAlgorithm = SHA512.Create(); + + if (hashAlgorithmName == HashAlgorithmName.MD5) + hashAlgorithm = MD5.Create(); + + if (hashAlgorithm == null) + throw new NullReferenceException($"{ nameof(hashAlgorithm) } was null."); + + byte[] bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + byte[] stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); + if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + else + { + return string.Empty; + } + } + + /// + /// Gets the ECDSA signature + /// + /// + /// ECDSA signature + private string GetECDSASignature(byte[] dataToSign) + { + {{#net60OrLater}} + if (!File.Exists(KeyFilePath) && string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + + var keyStr = KeyString; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + { + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + } + else + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + + var derBytes = ecdsa.SignHash(dataToSign, DSASignatureFormat.Rfc3279DerSequence); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; + {{/net60OrLater}} + {{^net60OrLater}} + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); + {{/net60OrLater}} + } + + /// + /// Convert ANS1 format to DER format. Not recommended to use because it generate inavlid signature occationally. + /// + /// + /// + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default length for ECDSA code signing bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + { + rBytes.Add(signedBytes[i]); + } + for (int i = 32; i < 64; i++) + { + sBytes.Add(signedBytes[i]); + } + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r length, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) + { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[] pemkey = null; + string pemstr = keyString; + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + { + isPrivateKeyFile = false; + } + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPhrase); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPhrase = null) + { + const string pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const string pemprivfooter = "-----END RSA PRIVATE KEY-----"; + string pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + { + return null; + } + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + string pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { + return null; + } + string saltline = str.ReadLine(); + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { + return null; + } + string saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + if (str.ReadLine() != "") + { + return null; + } + + //------ remaining b64 data is encrypted RSA key ---- + string encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 format + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + { + return null; + } + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + return rsakey; + } + } + + private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { + binr.ReadByte(); //advance 1 byte + } + else if (twobytes == 0x8230) + { + binr.ReadInt16(); //advance 2 bytes + } + else + { + return null; + } + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + { + return null; + } + bt = binr.ReadByte(); + if (bt != 0x00) + { + return null; + } + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + bytesModulus = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesE = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesD = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesIQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + { + return 0; + } + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + while (binr.ReadByte() == 0x00) + { + //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + const int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- concatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = MD5.Create(); + byte[] result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + { + result = data00; //initialize + } + else + { + Array.Copy(result, hashtarget, result.Length); + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + { + result = md5.ComputeHash(result); + } + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result, 0, result.Length); + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// api key in string format + /// Private Key Type + private PrivateKeyType GetKeyType(string keyString) + { + string[] key = null; + + if (string.IsNullOrEmpty(keyString)) + { + throw new Exception("No API key has been provided."); + } + + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + PrivateKeyType keyType; + key = KeyString.TrimEnd().Split('\n'); + + if (key[0].Contains(rsaPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + { + keyType = PrivateKeyType.RSA; + } + else if (key[0].Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + keyType = PrivateKeyType.ECDSA; + } + else + { + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); + } + return keyType; + } + + /// + /// Read the api key form the api key file path and stored it in KeyString property. + /// + /// api key file path + private string ReadApiKeyFromFile(string apiKeyFilePath) + { + string apiKeyString = null; + + if(File.Exists(apiKeyFilePath)) + { + apiKeyString = File.ReadAllText(apiKeyFilePath); + } + else + { + throw new Exception("Provided API key file path does not exists."); + } + return apiKeyString; + } + } +} diff --git a/generation/templates/IApiAccessor.mustache b/generation/templates/IApiAccessor.mustache new file mode 100644 index 00000000..a269f56e --- /dev/null +++ b/generation/templates/IApiAccessor.mustache @@ -0,0 +1,29 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + {{>visibility}} interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/generation/templates/IAsynchronousClient.mustache b/generation/templates/IAsynchronousClient.mustache new file mode 100644 index 00000000..f0c88fae --- /dev/null +++ b/generation/templates/IAsynchronousClient.mustache @@ -0,0 +1,92 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/generation/templates/IReadableConfiguration.mustache b/generation/templates/IReadableConfiguration.mustache new file mode 100644 index 00000000..78c998b3 --- /dev/null +++ b/generation/templates/IReadableConfiguration.mustache @@ -0,0 +1,172 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +{{#useRestSharp}} +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +{{/useRestSharp}} + +namespace {{packageName}}.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + {{#useRestSharp}} + {{#hasOAuthMethods}} + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + + {{/hasOAuthMethods}} + {{/useRestSharp}} + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time format. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + bool UseDefaultCredentials { get; } + + /// + /// Get the servers associated with the operation. + /// + /// Operation servers. + IReadOnlyDictionary>> OperationServers { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets the Operation server url at the provided index. + /// + /// Operation server name. + /// Index of the operation server settings. + /// + string GetOperationServerUrl(string operation, int index); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + {{#hasHttpSignatureMethods}} + + /// + /// Gets the HttpSigning configuration + /// + HttpSigningConfiguration HttpSigningConfiguration { get; } + {{/hasHttpSignatureMethods}} + + /// + /// Callback function for handling the validation of remote certificates. Useful for certificate pinning and + /// overriding certificate errors in the scope of a request. + /// + RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; } + } +} diff --git a/generation/templates/ISynchronousClient.mustache b/generation/templates/ISynchronousClient.mustache new file mode 100644 index 00000000..c09bfbfe --- /dev/null +++ b/generation/templates/ISynchronousClient.mustache @@ -0,0 +1,85 @@ +{{>partial_header}} + +using System; +using System.IO; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/generation/templates/JsonSubTypesTests.mustache b/generation/templates/JsonSubTypesTests.mustache new file mode 100644 index 00000000..55b1d518 --- /dev/null +++ b/generation/templates/JsonSubTypesTests.mustache @@ -0,0 +1,125 @@ +{{>partial_header}} + +using System.Collections.Generic; +using System.Linq; +using JsonSubTypes; +using Newtonsoft.Json; +using NUnit.Framework; + +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.Client; + +namespace {{packageName}}.Test.Client +{ + public class JsonSubTypesTests + { + [Test] + public void TestSimpleJsonSubTypesExample() + { + var animal = + JsonConvert.DeserializeObject("{\"Kind\":\"Dog\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (animal as Dog)?.Breed); + } + + [Test] + public void DeserializeObjectWithCustomMapping() + { + var animal = + JsonConvert.DeserializeObject("{\"Sound\":\"Bark\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (animal as Dog2)?.Breed); + } + + [Test] + public void DeserializeObjectMappingByPropertyPresence() + { + string json = + "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]"; + + + var persons = JsonConvert.DeserializeObject>(json); + Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill); + } + } + + [JsonConverter(typeof(JsonSubtypes), "Kind")] + public interface IAnimal + { + string Kind { get; } + } + + public class Dog : IAnimal + { + public Dog() + { + Kind = "Dog"; + } + + public string Kind { get; } + public string Breed { get; set; } + } + + class Cat : IAnimal + { + public Cat() + { + Kind = "Cat"; + } + + public string Kind { get; } + bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes), "Sound")] + [JsonSubtypes.KnownSubType(typeof(Dog2), "Bark")] + [JsonSubtypes.KnownSubType(typeof(Cat2), "Meow")] + public class Animal2 + { + public virtual string Sound { get; } + public string Color { get; set; } + } + + public class Dog2 : Animal2 + { + public Dog2() + { + Sound = "Bark"; + } + + public override string Sound { get; } + public string Breed { get; set; } + } + + public class Cat2 : Animal2 + { + public Cat2() + { + Sound = "Meow"; + } + + public override string Sound { get; } + public bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes))] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")] + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + } + + public class Employee : Person + { + public string Department { get; set; } + public string JobTitle { get; set; } + } + + public class Artist : Person + { + public string Skill { get; set; } + } +} diff --git a/generation/templates/Multimap.mustache b/generation/templates/Multimap.mustache new file mode 100644 index 00000000..8624af00 --- /dev/null +++ b/generation/templates/Multimap.mustache @@ -0,0 +1,287 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/generation/templates/NullConditionalParameter.mustache b/generation/templates/NullConditionalParameter.mustache new file mode 100644 index 00000000..d8ad9266 --- /dev/null +++ b/generation/templates/NullConditionalParameter.mustache @@ -0,0 +1 @@ +{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}} \ No newline at end of file diff --git a/generation/templates/NullConditionalProperty.mustache b/generation/templates/NullConditionalProperty.mustache new file mode 100644 index 00000000..7dcafa80 --- /dev/null +++ b/generation/templates/NullConditionalProperty.mustache @@ -0,0 +1 @@ +{{#lambda.first}}{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} \ No newline at end of file diff --git a/generation/templates/OpenAPIDateConverter.mustache b/generation/templates/OpenAPIDateConverter.mustache new file mode 100644 index 00000000..d7905102 --- /dev/null +++ b/generation/templates/OpenAPIDateConverter.mustache @@ -0,0 +1,21 @@ +{{>partial_header}} +using Newtonsoft.Json.Converters; + +namespace {{packageName}}.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/generation/templates/README.mustache b/generation/templates/README.mustache new file mode 100644 index 00000000..9b6c23b9 --- /dev/null +++ b/generation/templates/README.mustache @@ -0,0 +1,267 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Frameworks supported +{{#netStandard}} +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext +{{/netStandard}} + + +## Dependencies + +{{#useRestSharp}} +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.13.0 or later +{{/useRestSharp}} +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.2 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +{{#useCompareNetObjects}} +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +{{/useCompareNetObjects}} +{{#validatable}} +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later +{{/validatable}} + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +{{#useRestSharp}} +Install-Package RestSharp +{{/useRestSharp}} +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +{{#validatable}} +Install-Package System.ComponentModel.Annotations +{{/validatable}} +{{#useCompareNetObjects}} +Install-Package CompareNETObjects +{{/useCompareNetObjects}} +``` +{{#useRestSharp}} + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + +{{/useRestSharp}} + +## Installation +{{#netStandard}} +Generate the DLL using your preferred tool (e.g. `dotnet build`) +{{/netStandard}} +{{^netStandard}} +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` +{{/netStandard}} + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; +``` +{{^netStandard}} + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out {{packageName}}.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + +{{/netStandard}} + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` +{{#useHttpClient}} + +### Connections +Each ApiClass (properly the ApiClient inside it) will create an instance of HttpClient. It will use that for the entire lifecycle and dispose it when called the Dispose method. + +To better manager the connections it's a common practice to reuse the HttpClient and HttpClientHandler (see [here](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net) for details). To use your own HttpClient instance just pass it to the ApiClass constructor. + +```csharp +HttpClientHandler yourHandler = new HttpClientHandler(); +HttpClient yourHttpClient = new HttpClient(yourHandler); +var api = new YourApiClass(yourHttpClient, yourHandler); +``` + +If you want to use an HttpClient and don't have access to the handler, for example in a DI context in Asp.net Core when using IHttpClientFactory. + +```csharp +HttpClient yourHttpClient = new HttpClient(); +var api = new YourApiClass(yourHttpClient); +``` +You'll loose some configuration settings, the features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. You need to either manually handle those in your setup of the HttpClient or they won't be available. + +Here an example of DI setup in a sample web project: + +```csharp +services.AddHttpClient(httpClient => + new PetApi(httpClient)); +``` + +{{/useHttpClient}} + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{{summary}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: Bearer Authentication +{{/isBasicBearer}} +{{#isHttpSignature}}- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/generation/templates/ReadOnlyDictionary.mustache b/generation/templates/ReadOnlyDictionary.mustache new file mode 100644 index 00000000..1299b243 --- /dev/null +++ b/generation/templates/ReadOnlyDictionary.mustache @@ -0,0 +1,137 @@ +{{>partial_header}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace {{packageName}}.Client +{ + public class ReadOnlyDictionary : IDictionary + { + private IDictionary _dictionaryImplementation; + public IEnumerator> GetEnumerator() + { + return _dictionaryImplementation.GetEnumerator(); + } + + public ReadOnlyDictionary() + { + _dictionaryImplementation = new Dictionary(); + } + + public ReadOnlyDictionary(IDictionary dictionaryImplementation) + { + if (dictionaryImplementation == null) throw new ArgumentNullException("dictionaryImplementation"); + _dictionaryImplementation = dictionaryImplementation; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _dictionaryImplementation).GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public void Clear() + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool Contains(KeyValuePair item) + { + return _dictionaryImplementation.Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + _dictionaryImplementation.CopyTo(array, arrayIndex); + } + + public bool Remove(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public int Count + { + get { return _dictionaryImplementation.Count; } + } + + public bool IsReadOnly + { + get { return true; } + } + + public void Add(T key, K value) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool ContainsKey(T key) + { + return _dictionaryImplementation.ContainsKey(key); + } + + public bool Remove(T key) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool TryGetValue(T key, out K value) + { + return _dictionaryImplementation.TryGetValue(key, out value); + } + + public K this[T key] + { + get { return _dictionaryImplementation[key]; } + set + { + throw new ReadonlyOperationException("This instance is readonly."); + + } + } + + public ICollection Keys + { + get { return _dictionaryImplementation.Keys; } + } + + public ICollection Values + { + get { return _dictionaryImplementation.Values; } + } + } + + [Serializable] + public class ReadonlyOperationException : Exception + { + // + // For guidelines regarding the creation of new exception types, see + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp + // and + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp + // + + public ReadonlyOperationException() + { + } + + public ReadonlyOperationException(string message) : base(message) + { + } + + public ReadonlyOperationException(string message, Exception inner) : base(message, inner) + { + } + + protected ReadonlyOperationException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { + } + } +} diff --git a/generation/templates/RequestOptions.mustache b/generation/templates/RequestOptions.mustache new file mode 100644 index 00000000..cfc14692 --- /dev/null +++ b/generation/templates/RequestOptions.mustache @@ -0,0 +1,87 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + {{#supportsFileParameters}} + /// + /// File parameters to be sent along with the request. + /// + public Multimap FileParameters { get; set; } + {{/supportsFileParameters}} + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Operation associated with the request path. + /// + public string Operation { get; set; } + + /// + /// Index associated with the operation. + /// + public int OperationIndex { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + {{#hasOAuthMethods}} + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + + {{/hasOAuthMethods}} + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + {{#supportsFileParameters}} + FileParameters = new Multimap(); + {{/supportsFileParameters}} + Cookies = new List(); + } + } +} diff --git a/generation/templates/RetryConfiguration.mustache b/generation/templates/RetryConfiguration.mustache new file mode 100644 index 00000000..93ba14d9 --- /dev/null +++ b/generation/templates/RetryConfiguration.mustache @@ -0,0 +1,41 @@ +{{>partial_header}} + +using Polly; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} + +namespace {{packageName}}.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public static class RetryConfiguration + { +{{#useRestSharp}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useRestSharp}} +{{#useHttpClient}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useHttpClient}} + } +} diff --git a/generation/templates/Solution.mustache b/generation/templates/Solution.mustache new file mode 100644 index 00000000..112cc3dc --- /dev/null +++ b/generation/templates/Solution.mustache @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio {{^netStandard}}2012{{/netStandard}}{{#netStandard}}14{{/netStandard}} +VisualStudioVersion = {{^netStandard}}12.0.0.0{{/netStandard}}{{#netStandard}}14.0.25420.1{{/netStandard}} +MinimumVisualStudioVersion = {{^netStandard}}10.0.0.1{{/netStandard}}{{#netStandard}}10.0.40219.1{{/netStandard}} +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" +EndProject +{{^excludeTests}}Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +{{/excludeTests}}Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU + {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU + {{packageGuid}}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/generation/templates/TestProject.mustache b/generation/templates/TestProject.mustache new file mode 100644 index 00000000..2a27f6a9 --- /dev/null +++ b/generation/templates/TestProject.mustache @@ -0,0 +1,35 @@ + + + + + false + Properties + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false + 512 + + + + + + + + + {{packageGuid}} + {{packageName}} + + + diff --git a/generation/templates/ValidateRegex.mustache b/generation/templates/ValidateRegex.mustache new file mode 100644 index 00000000..15cf626d --- /dev/null +++ b/generation/templates/ValidateRegex.mustache @@ -0,0 +1,6 @@ +// {{{name}}} ({{{dataType}}}) pattern +Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); +if (!regex{{{name}}}.Match(this.{{{name}}}{{#isUuid}}.ToString(){{/isUuid}}).Success) +{ + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); +} \ No newline at end of file diff --git a/generation/templates/WebRequestPathBuilder.mustache b/generation/templates/WebRequestPathBuilder.mustache new file mode 100644 index 00000000..cc811ae4 --- /dev/null +++ b/generation/templates/WebRequestPathBuilder.mustache @@ -0,0 +1,45 @@ +{{>partial_header}} +using System; +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A URI builder + /// + class WebRequestPathBuilder + { + private string _baseUrl; + private string _path; + private string _query = "?"; + public WebRequestPathBuilder(string baseUrl, string path) + { + _baseUrl = baseUrl; + _path = path; + } + + public void AddPathParameters(Dictionary parameters) + { + foreach (var parameter in parameters) + { + _path = _path.Replace("{" + parameter.Key + "}", Uri.EscapeDataString(parameter.Value)); + } + } + + public void AddQueryParameters(Multimap parameters) + { + foreach (var parameter in parameters) + { + foreach (var value in parameter.Value) + { + _query = _query + parameter.Key + "=" + Uri.EscapeDataString(value) + "&"; + } + } + } + + public string GetFullUri() + { + return _baseUrl + _path + _query.Substring(0, _query.Length - 1); + } + } +} diff --git a/generation/templates/api.mustache b/generation/templates/api.mustache new file mode 100644 index 00000000..6494627b --- /dev/null +++ b/generation/templates/api.mustache @@ -0,0 +1,798 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{.}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// Index associated with the operation. + /// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// Index associated with the operation. + /// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// Index associated with the operation. + /// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// Index associated with the operation. + /// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + { + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + } + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{paramName}}[{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}]", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + {{#isArray}} + {{#supportsFileParameters}} + foreach (var file in {{paramName}}) + { + localVarRequestOptions.FileParameters.Add("{{baseName}}", file); + } + {{/supportsFileParameters}} + {{/isArray}} + {{^isArray}} + {{#supportsFileParameters}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/supportsFileParameters}} + {{/isArray}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + {{#isArray}} + {{#supportsFileParameters}} + foreach (var file in {{paramName}}) + { + localVarRequestOptions.FileParameters.Add("{{baseName}}", file); + } + {{/supportsFileParameters}} + {{/isArray}} + {{^isArray}} + {{#supportsFileParameters}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/supportsFileParameters}} + {{/isArray}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + localVarRequestOptions.Operation = "{{classname}}.{{operationId}}"; + localVarRequestOptions.OperationIndex = operationIndex; + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{#hasOAuthMethods}} + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + {{/hasOAuthMethods}} + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}operationIndex, cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + { + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + } + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + {{#constantParams}} + {{#isPathParam}} + // Set client side default value of Path Param "{{baseName}}". + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant path parameter + {{/isPathParam}} + {{/constantParams}} + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + localVarRequestOptions.QueryParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant query parameter + {{/isQueryParam}} + {{/constantParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{paramName}}[{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}]", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#constantParams}} + {{#isHeaderParam}} + // Set client side default value of Header Param "{{baseName}}". + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant header parameter + {{/isHeaderParam}} + {{/constantParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + {{#isArray}} + {{#supportsFileParameters}} + foreach (var file in {{paramName}}) + { + localVarRequestOptions.FileParameters.Add("{{baseName}}", file); + } + {{/supportsFileParameters}} + {{/isArray}} + {{^isArray}} + {{#supportsFileParameters}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/supportsFileParameters}} + {{/isArray}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + {{#isArray}} + {{#supportsFileParameters}} + foreach (var file in {{paramName}}) + { + localVarRequestOptions.FileParameters.Add("{{baseName}}", file); + } + {{/supportsFileParameters}} + {{/isArray}} + {{^isArray}} + {{#supportsFileParameters}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/supportsFileParameters}} + {{/isArray}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + localVarRequestOptions.Operation = "{{classname}}.{{operationId}}"; + localVarRequestOptions.OperationIndex = operationIndex; + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{#hasOAuthMethods}} + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + {{/hasOAuthMethods}} + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/generation/templates/api_doc.mustache b/generation/templates/api_doc.mustache new file mode 100644 index 00000000..da165463 --- /dev/null +++ b/generation/templates/api_doc.mustache @@ -0,0 +1,162 @@ +# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}} +{{.}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +{{#operations}} +{{#operation}} +| [**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}} | +{{/operation}} +{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{{operationId}}}** +> {{returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{.}}}{{/notes}} + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.AddApiKey("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the {{operationId}}WithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}ApiResponse<{{{.}}}> response = {{/returnType}}apiInstance.{{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data);{{/returnType}} +} +catch (ApiException e) +{ + Debug.Print("Exception when calling {{classname}}.{{operationId}}WithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | Notes | +|------|------|-------------|-------| +{{/-last}} +{{/allParams}} +{{#allParams}} +| **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{#isContainer}}{{baseType}}{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +[[Back to top]](#) [[Back to API list]](../{{#useGenericHost}}../{{/useGenericHost}}README.md#documentation-for-api-endpoints) [[Back to Model list]](../{{#useGenericHost}}../{{/useGenericHost}}README.md#documentation-for-models) [[Back to README]](../{{#useGenericHost}}../{{/useGenericHost}}README.md) + +{{/operation}} +{{/operations}} diff --git a/generation/templates/api_test.mustache b/generation/templates/api_test.mustache new file mode 100644 index 00000000..78319978 --- /dev/null +++ b/generation/templates/api_test.mustache @@ -0,0 +1,77 @@ +{{>partial_header}} +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +using Xunit; + +using {{packageName}}.Client; +using {{packageName}}.{{apiPackage}}; +{{#hasImport}} +// uncomment below to import models +//using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.Test.Api +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class {{classname}}Tests : IDisposable + { + {{^nonPublicApi}} + private {{classname}} instance; + + {{/nonPublicApi}} + public {{classname}}Tests() + { + {{^nonPublicApi}} + instance = new {{classname}}(); + {{/nonPublicApi}} + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{operationId}}InstanceTest() + { + // TODO uncomment below to test 'IsType' {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}} + /// + [Fact] + public void {{operationId}}Test() + { + // TODO uncomment below to test the method and replace null with proper value + {{#allParams}} + //{{{dataType}}} {{paramName}} = null; + {{/allParams}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}} + //Assert.IsType<{{{.}}}>(response); + {{/returnType}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/generation/templates/appveyor.mustache b/generation/templates/appveyor.mustache new file mode 100644 index 00000000..eb85fc2a --- /dev/null +++ b/generation/templates/appveyor.mustache @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\{{{packageName}}}\{{{packageName}}}.csproj -o ../../output -c Release --no-build diff --git a/generation/templates/auth/OAuthAuthenticator.mustache b/generation/templates/auth/OAuthAuthenticator.mustache new file mode 100644 index 00000000..ae8f3c75 --- /dev/null +++ b/generation/templates/auth/OAuthAuthenticator.mustache @@ -0,0 +1,97 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace {{packageName}}.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken().ConfigureAwait(false) : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration))); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request).ConfigureAwait(false); + + // RFC6749 - token_type is case insensitive. + // RFC6750 - In Authorization header Bearer should be capitalized. + // Fix the capitalization irrespective of token_type casing. + switch (response.TokenType?.ToLower()) + { + case "bearer": + return $"Bearer {response.AccessToken}"; + default: + return $"{response.TokenType} {response.AccessToken}"; + } + } + } +} diff --git a/generation/templates/auth/OAuthFlow.mustache b/generation/templates/auth/OAuthFlow.mustache new file mode 100644 index 00000000..768ddd0a --- /dev/null +++ b/generation/templates/auth/OAuthFlow.mustache @@ -0,0 +1,19 @@ +{{>partial_header}} + +namespace {{packageName}}.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/generation/templates/auth/TokenResponse.mustache b/generation/templates/auth/TokenResponse.mustache new file mode 100644 index 00000000..f118b97a --- /dev/null +++ b/generation/templates/auth/TokenResponse.mustache @@ -0,0 +1,14 @@ +{{>partial_header}} + +using Newtonsoft.Json; + +namespace {{packageName}}.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/generation/templates/git_push.sh.mustache b/generation/templates/git_push.sh.mustache new file mode 100644 index 00000000..0e3776ae --- /dev/null +++ b/generation/templates/git_push.sh.mustache @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/generation/templates/gitignore.mustache b/generation/templates/gitignore.mustache new file mode 100644 index 00000000..1ee53850 --- /dev/null +++ b/generation/templates/gitignore.mustache @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/generation/templates/libraries/generichost/AfterOperationDefaultImplementation.mustache b/generation/templates/libraries/generichost/AfterOperationDefaultImplementation.mustache new file mode 100644 index 00000000..394c6572 --- /dev/null +++ b/generation/templates/libraries/generichost/AfterOperationDefaultImplementation.mustache @@ -0,0 +1,2 @@ + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ApiException.mustache b/generation/templates/libraries/generichost/ApiException.mustache new file mode 100644 index 00000000..c14c1010 --- /dev/null +++ b/generation/templates/libraries/generichost/ApiException.mustache @@ -0,0 +1,46 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// API Exception + /// + {{>visibility}} class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string{{nrt?}} ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string{{nrt?}} reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/generation/templates/libraries/generichost/ApiFactory.mustache b/generation/templates/libraries/generichost/ApiFactory.mustache new file mode 100644 index 00000000..a445d216 --- /dev/null +++ b/generation/templates/libraries/generichost/ApiFactory.mustache @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{apiPackage}}; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// An IApiFactory interface + /// + {{>visibility}} interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi; + } + + /// + /// An ApiFactory + /// + {{>visibility}} class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/generation/templates/libraries/generichost/ApiKeyToken.mustache b/generation/templates/libraries/generichost/ApiKeyToken.mustache new file mode 100644 index 00000000..273eb2cc --- /dev/null +++ b/generation/templates/libraries/generichost/ApiKeyToken.mustache @@ -0,0 +1,56 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed from an apiKey. + /// + {{>visibility}} class ApiKeyToken : TokenBase + { + private string _raw; + + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs an ApiKeyToken object. + /// + /// + /// + /// + /// + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + { + Header = header; + _raw = $"{ prefix }{ value }"; + } + + /// + /// Places the token in the header. + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); + } + + /// + /// Places the token in the query. + /// + /// + /// + /// + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) + { + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString(){{nrt!}}; + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ApiResponseEventArgs`1.mustache b/generation/templates/libraries/generichost/ApiResponseEventArgs`1.mustache new file mode 100644 index 00000000..aea35fae --- /dev/null +++ b/generation/templates/libraries/generichost/ApiResponseEventArgs`1.mustache @@ -0,0 +1,24 @@ +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Useful for tracking server health + /// + {{>visibility}} class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/generation/templates/libraries/generichost/ApiResponse`1.mustache b/generation/templates/libraries/generichost/ApiResponse`1.mustache new file mode 100644 index 00000000..5b097c22 --- /dev/null +++ b/generation/templates/libraries/generichost/ApiResponse`1.mustache @@ -0,0 +1,170 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +{{^netStandard}} +using System.Diagnostics.CodeAnalysis; +{{/netStandard}} +using System.Net; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + {{>visibility}} partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the api response + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the api response + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the api response + /// + string{{nrt?}} ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri{{nrt?}} RequestUri { get; } + } + + /// + /// API Response + /// + {{>visibility}} partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data + /// + public string RawContent { get; protected set; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string{{nrt?}} ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri{{nrt?}} RequestUri { get; } + + /// + /// The + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + } + {{#x-http-statuses-with-return}} + + /// + /// An interface for responses of type {{TType}} + /// + /// + {{>visibility}} interface I{{.}} : IApiResponse + { + /// + /// Deserializes the response if the response is {{.}} + /// + /// + TType {{.}}(); + + /// + /// Returns true if the response is {{.}} and the deserialized response is not null + /// + /// + /// + bool Try{{.}}({{#net60OrLater}}[NotNullWhen(true)]{{/net60OrLater}}out TType{{nrt?}} result); + } + {{/x-http-statuses-with-return}} +} diff --git a/generation/templates/libraries/generichost/ApiTestsBase.mustache b/generation/templates/libraries/generichost/ApiTestsBase.mustache new file mode 100644 index 00000000..3292a1e8 --- /dev/null +++ b/generation/templates/libraries/generichost/ApiTestsBase.mustache @@ -0,0 +1,65 @@ +{{>partial_header}} +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using {{packageName}}.{{clientPackage}};{{#hasImport}} +using {{packageName}}.{{modelPackage}};{{/hasImport}} +using {{packageName}}.Extensions; + + +{{>testInstructions}} + + +namespace {{packageName}}.Test.{{apiPackage}} +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .Configure{{apiName}}((context, services, options) => + { + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + string apiKeyTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}(apiKeyTokenValue{{-index}}, ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + string bearerTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}(bearerTokenValue{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + string basicTokenUsername{{-index}} = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword{{-index}} = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}(basicTokenUsername{{-index}}, basicTokenPassword{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + string oauthTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}(oauthTokenValue{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} + }); + } +} diff --git a/generation/templates/libraries/generichost/AsModel.mustache b/generation/templates/libraries/generichost/AsModel.mustache new file mode 100644 index 00000000..96bedfa4 --- /dev/null +++ b/generation/templates/libraries/generichost/AsModel.mustache @@ -0,0 +1,4 @@ +// This logic may be modified with the AsModel.mustache template +return Is{{vendorExtensions.x-http-status}} + ? System.Text.Json.JsonSerializer.Deserialize<{{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}>(RawContent, _jsonSerializerOptions) + : {{#net60OrLater}}null{{/net60OrLater}}{{^net60OrLater}}default{{/net60OrLater}}; diff --git a/generation/templates/libraries/generichost/Assembly.mustache b/generation/templates/libraries/generichost/Assembly.mustache new file mode 100644 index 00000000..a22cc232 --- /dev/null +++ b/generation/templates/libraries/generichost/Assembly.mustache @@ -0,0 +1,2 @@ +[assembly: InternalsVisibleTo("{{packageName}}.Test")] + diff --git a/generation/templates/libraries/generichost/BasicToken.mustache b/generation/templates/libraries/generichost/BasicToken.mustache new file mode 100644 index 00000000..4cb7023f --- /dev/null +++ b/generation/templates/libraries/generichost/BasicToken.mustache @@ -0,0 +1,46 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed from a username and password. + /// + {{>visibility}} class BasicToken : TokenBase + { + private string _username; + + private string _password; + + /// + /// Constructs a BasicToken object. + /// + /// + /// + /// + public BasicToken(string username, string password, TimeSpan? timeout = null) : base(timeout) + { + _username = username; + + _password = password; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", {{packageName}}.Client.ClientUtils.Base64Encode(_username + ":" + _password)); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/BearerToken.mustache b/generation/templates/libraries/generichost/BearerToken.mustache new file mode 100644 index 00000000..b0fc0a5d --- /dev/null +++ b/generation/templates/libraries/generichost/BearerToken.mustache @@ -0,0 +1,41 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed from a token from a bearer token. + /// + {{>visibility}} class BearerToken : TokenBase + { + private string _raw; + + /// + /// Constructs a BearerToken object. + /// + /// + /// + public BearerToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ClientUtils.mustache b/generation/templates/libraries/generichost/ClientUtils.mustache new file mode 100644 index 00000000..271dfa67 --- /dev/null +++ b/generation/templates/libraries/generichost/ClientUtils.mustache @@ -0,0 +1,401 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions;{{#useCompareNetObjects}} +using KellermanSoftware.CompareNetObjects;{{/useCompareNetObjects}} +using {{packageName}}.{{modelPackage}}; +using System.Runtime.CompilerServices; + +{{>Assembly}}namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + {{>visibility}} static class ClientUtils + { + {{#useCompareNetObjects}} + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + {{#equatable}} + ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}(); + comparisonConfig.UseHashCodeIdentifier = true; + {{/equatable}} + compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}}); + } + {{/useCompareNetObjects}} + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + {{#hasApiKeyMethods}} + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + {{#apiKeyMethods}} + /// + /// The {{keyParamName}} header + /// + {{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}{{^-last}},{{/-last}} + {{/apiKeyMethods}} + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + {{>visibility}} static string ApiKeyHeaderToString(ApiKeyHeader value) + { + {{#net80OrLater}} + return value switch + { + {{#apiKeyMethods}} + ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}} => "{{keyParamName}}", + {{/apiKeyMethods}} + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + {{/net80OrLater}} + {{^net80OrLater}} + switch(value) + { + {{#apiKeyMethods}} + case ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}: + return "{{keyParamName}}"; + {{/apiKeyMethods}} + default: + throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)); + } + {{/net80OrLater}} + } + + {{/hasApiKeyMethods}} + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, {{#net60OrLater}}[System.Diagnostics.CodeAnalysis.NotNullWhen(true)] {{/net60OrLater}}out T{{#nrt}}{{#net60OrLater}}?{{/net60OrLater}}{{/nrt}} result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, {{#net60OrLater}}[System.Diagnostics.CodeAnalysis.NotNullWhen(true)] {{/net60OrLater}}out T{{#nrt}}{{#net60OrLater}}?{{/net60OrLater}}{{/nrt}} result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string{{nrt?}} ParameterToString(object{{nrt?}} obj, string{{nrt?}} format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean + ? "true" + : "false"; + {{#models}} + {{#model}} + {{#isEnum}} + if (obj is {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return {{classname}}ValueConverter.{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/isEnum}} + {{^isEnum}} + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} + if (obj is {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} + if (obj is {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/complexType}} + {{/isEnum}} + {{/vars}} + {{/isEnum}} + {{/model}} + {{/models}} + if (obj is ICollection collection) + { + List entries = new{{^net70OrLater}} List{{/net70OrLater}}(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string{{nrt?}} SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string{{nrt?}} SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string{{nrt?}} GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string{{nrt?}} localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (localVarJsonPropertyName != null && localVarJsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "{{{basePath}}}"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "{{{scheme}}}"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = "{{contextPath}}"; + + /// + /// The host of the API + /// + public const string HOST = "{{{host}}}"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/generation/templates/libraries/generichost/CookieContainer.mustache b/generation/templates/libraries/generichost/CookieContainer.mustache new file mode 100644 index 00000000..f96d4fb4 --- /dev/null +++ b/generation/templates/libraries/generichost/CookieContainer.mustache @@ -0,0 +1,22 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Linq; +using System.Collections.Generic; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A class containing a CookieContainer + /// + {{>visibility}} sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/DateFormats.mustache b/generation/templates/libraries/generichost/DateFormats.mustache new file mode 100644 index 00000000..920ecda8 --- /dev/null +++ b/generation/templates/libraries/generichost/DateFormats.mustache @@ -0,0 +1,2 @@ + "yyyy'-'MM'-'dd", + "yyyyMMdd" diff --git a/generation/templates/libraries/generichost/DateOnlyJsonConverter.mustache b/generation/templates/libraries/generichost/DateOnlyJsonConverter.mustache new file mode 100644 index 00000000..209979c8 --- /dev/null +++ b/generation/templates/libraries/generichost/DateOnlyJsonConverter.mustache @@ -0,0 +1,51 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } +} diff --git a/generation/templates/libraries/generichost/DateOnlyNullableJsonConverter.mustache b/generation/templates/libraries/generichost/DateOnlyNullableJsonConverter.mustache new file mode 100644 index 00000000..17c84736 --- /dev/null +++ b/generation/templates/libraries/generichost/DateOnlyNullableJsonConverter.mustache @@ -0,0 +1,56 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } + } +} diff --git a/generation/templates/libraries/generichost/DateTimeFormats.mustache b/generation/templates/libraries/generichost/DateTimeFormats.mustache new file mode 100644 index 00000000..85ed99a2 --- /dev/null +++ b/generation/templates/libraries/generichost/DateTimeFormats.mustache @@ -0,0 +1,22 @@ + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + {{^supportsDateOnly}} + "yyyy'-'MM'-'dd", + {{/supportsDateOnly}} + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + {{^supportsDateOnly}} + "yyyyMMdd" + {{/supportsDateOnly}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/DateTimeJsonConverter.mustache b/generation/templates/libraries/generichost/DateTimeJsonConverter.mustache new file mode 100644 index 00000000..c5187f50 --- /dev/null +++ b/generation/templates/libraries/generichost/DateTimeJsonConverter.mustache @@ -0,0 +1,51 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateTimeFormats}} + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString("{{{dateTimeFormat}}}", CultureInfo.InvariantCulture)); + } +} diff --git a/generation/templates/libraries/generichost/DateTimeNullableJsonConverter.mustache b/generation/templates/libraries/generichost/DateTimeNullableJsonConverter.mustache new file mode 100644 index 00000000..646c7294 --- /dev/null +++ b/generation/templates/libraries/generichost/DateTimeNullableJsonConverter.mustache @@ -0,0 +1,56 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateTimeFormats}} + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString("{{{dateTimeFormat}}}", CultureInfo.InvariantCulture)); + } + } +} diff --git a/generation/templates/libraries/generichost/DependencyInjectionTests.mustache b/generation/templates/libraries/generichost/DependencyInjectionTests.mustache new file mode 100644 index 00000000..aadf2c73 --- /dev/null +++ b/generation/templates/libraries/generichost/DependencyInjectionTests.mustache @@ -0,0 +1,211 @@ +{{>partial_header}} +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using {{packageName}}.{{clientPackage}}; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Extensions; +using Xunit; + +namespace {{packageName}}.Test.{{apiPackage}} +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).Configure{{apiName}}((context, services, options) => + { + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).Configure{{apiName}}((context, services, options) => + { + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} + options.Add{{apiName}}HttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).ConfigureServices((host, services) => + { + services.Add{{apiName}}(options => + { + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).ConfigureServices((host, services) => + { + services.Add{{apiName}}(options => + { + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} + options.Add{{apiName}}HttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + {{#apiInfo}}{{#apis}}var {{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}} = _hostUsingConfigureWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + Assert.True({{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}}.HttpClient.BaseAddress != null);{{^-last}} + + {{/-last}}{{/apis}}{{/apiInfo}} + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + {{#apiInfo}}{{#apis}}var {{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}} = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + Assert.True({{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}}.HttpClient.BaseAddress != null);{{^-last}} + + {{/-last}}{{/apis}}{{/apiInfo}} + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + {{#apiInfo}}{{#apis}}var {{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}} = _hostUsingAddWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + Assert.True({{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}}.HttpClient.BaseAddress != null);{{^-last}} + + {{/-last}}{{/apis}}{{/apiInfo}} + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + {{#apiInfo}}{{#apis}}var {{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}} = _hostUsingAddWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + Assert.True({{#lambda.camel_case}}{{classname}}{{/lambda.camel_case}}.HttpClient.BaseAddress != null);{{^-last}} + + {{/-last}}{{/apis}}{{/apiInfo}} + } + } +} diff --git a/generation/templates/libraries/generichost/EnumValueDataType.mustache b/generation/templates/libraries/generichost/EnumValueDataType.mustache new file mode 100644 index 00000000..e92e67b3 --- /dev/null +++ b/generation/templates/libraries/generichost/EnumValueDataType.mustache @@ -0,0 +1 @@ +{{#allowableValues}}{{#enumVars}}{{#-first}}{{#isString}}{{^isNumeric}}string{{/isNumeric}}{{/isString}}{{#isNumeric}}{{#isLong}}long{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}double{{/isDouble}}{{#isDecimal}}decimal{{/isDecimal}}{{^isLong}}{{^isFloat}}{{^isDouble}}{{^isDecimal}}int{{/isDecimal}}{{/isDouble}}{{/isFloat}}{{/isLong}}{{/isNumeric}}{{/-first}}{{/enumVars}}{{/allowableValues}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ExceptionEventArgs.mustache b/generation/templates/libraries/generichost/ExceptionEventArgs.mustache new file mode 100644 index 00000000..016ef7c6 --- /dev/null +++ b/generation/templates/libraries/generichost/ExceptionEventArgs.mustache @@ -0,0 +1,24 @@ +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Useful for tracking server health + /// + {{>visibility}} class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExcepetionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/generation/templates/libraries/generichost/HostConfiguration.mustache b/generation/templates/libraries/generichost/HostConfiguration.mustache new file mode 100644 index 00000000..d7d1e3bf --- /dev/null +++ b/generation/templates/libraries/generichost/HostConfiguration.mustache @@ -0,0 +1,162 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides hosting configuration for {{packageName}} + /// + {{>visibility}} class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + {{#supportsDateOnly}} + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + {{/supportsDateOnly}} + {{#models}} + {{#model}} + {{#isEnum}} + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}JsonConverter()); + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableJsonConverter()); + {{/isEnum}} + {{^isEnum}} + _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); + {{/isEnum}} + {{/model}} + {{/models}} + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new{{^net60OrLater}} JsonSerializerOptionsProvider{{/net60OrLater}}(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + {{#useSourceGeneration}} + + {{#models}} + {{#-first}} + _jsonOptions.TypeInfoResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine( + {{/-first}} + {{/models}} + {{#lambda.joinLinesWithComma}} + {{#models}} + {{#model}} + new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}SerializationContext(){{#-last}},{{/-last}} + {{/model}} + {{/models}} + {{/lambda.joinLinesWithComma}} + {{#models}} + {{#-last}} + + new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver() + ); + {{/-last}} + {{/models}} + + {{/useSourceGeneration}} + _services.AddSingleton();{{#apiInfo}}{{#apis}} + _services.AddSingleton<{{classname}}Events>(); + _services.AddTransient<{{interfacePrefix}}{{classname}}, {{classname}}>();{{/apis}}{{/apiInfo}} + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration Add{{apiName}}HttpClients + ( + Action{{nrt?}} client = null, Action{{nrt?}} builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + {{#apiInfo}}{{#apis}}builders.Add(_services.AddHttpClient<{{interfacePrefix}}{{classname}}, {{classname}}>(client)); + {{/apis}}{{/apiInfo}} + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/generation/templates/libraries/generichost/HttpSigningConfiguration.mustache b/generation/templates/libraries/generichost/HttpSigningConfiguration.mustache new file mode 100644 index 00000000..2e99b3c9 --- /dev/null +++ b/generation/templates/libraries/generichost/HttpSigningConfiguration.mustache @@ -0,0 +1,678 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + {{>visibility}} class HttpSigningConfiguration + { + /// + /// Create an instance + /// + public HttpSigningConfiguration(string keyId, string keyFilePath, SecureString{{nrt?}} keyPassPhrase, List httpSigningHeader, HashAlgorithmName hashAlgorithm, string signingAlgorithm, int signatureValidityPeriod) + { + KeyId = keyId; + KeyFilePath = keyFilePath; + KeyPassPhrase = keyPassPhrase; + HttpSigningHeader = httpSigningHeader; + HashAlgorithm = hashAlgorithm; + SigningAlgorithm = signingAlgorithm; + SignatureValidityPeriod = signatureValidityPeriod; + } + + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString{{nrt?}} KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } = HashAlgorithmName.SHA256; + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validaty period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + + /// + /// Gets the Headers for HttpSigning + /// + /// + /// + /// + internal Dictionary GetHttpSignedHeader(System.Net.Http.HttpRequestMessage request, string requestBody, System.Threading.CancellationToken cancellationToken = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) + { + if (request.RequestUri == null) + throw new NullReferenceException("The request URI was null"); + + const string HEADER_REQUEST_TARGET = "(request-target)"; + + // The time when the HTTP signature expires. The API server should reject HTTP requests that have expired. + const string HEADER_EXPIRES = "(expires)"; + + //The 'Date' header. + const string HEADER_DATE = "Date"; + + //The 'Host' header. + const string HEADER_HOST = "Host"; + + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + + var httpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + HttpSigningHeader.Add("(created)"); + + var dateTime = DateTime.Now; + string digest = String.Empty; + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + + foreach (var header in HttpSigningHeader) + if (header.Equals(HEADER_REQUEST_TARGET)) + httpSignatureHeader.Add(header.ToLower(), request.RequestUri.ToString()); + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + httpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToString("r").ToString(); + httpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + httpSignatureHeader.Add(header.ToLower(), request.RequestUri.ToString()); + HttpSignedRequestHeader.Add(HEADER_HOST, request.RequestUri.ToString()); + } + else if (header.Equals(HEADER_CREATED)) + httpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, digest); + httpSignatureHeader.Add(header.ToLower(), digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in request.Headers) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + httpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + + if (!isHeaderFound) + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + + var headersKeysString = String.Join(" ", httpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in httpSignatureHeader) + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + + //Concatenate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm, headerValuesString); + string{{nrt?}} headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + headerSignatureStr = GetRSASignature(signatureStringHash); + + else if (keyType == PrivateKeyType.ECDSA) + headerSignatureStr = GetECDSASignature(signatureStringHash); + + var cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (httpSignatureHeader.ContainsKey(HEADER_CREATED)) + authorizationHeaderValue += string.Format(",created={0}", httpSignatureHeader[HEADER_CREATED]); + + if (httpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + authorizationHeaderValue += string.Format(",expires={0}", httpSignatureHeader[HEADER_EXPIRES]); + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); + + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(HashAlgorithmName hashAlgorithmName, string stringToBeHashed) + { + HashAlgorithm{{nrt?}} hashAlgorithm = null; + + if (hashAlgorithmName == HashAlgorithmName.SHA1) + hashAlgorithm = SHA1.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA256) + hashAlgorithm = SHA256.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA512) + hashAlgorithm = SHA512.Create(); + + if (hashAlgorithmName == HashAlgorithmName.MD5) + hashAlgorithm = MD5.Create(); + + if (hashAlgorithm == null) + throw new NullReferenceException($"{ nameof(hashAlgorithm) } was null."); + + byte[] bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + byte[] stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + if (KeyPassPhrase == null) + throw new NullReferenceException($"{ nameof(KeyPassPhrase) } was null."); + + RSA{{nrt?}} rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + + if (rsa == null) + return string.Empty; + else if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + + return string.Empty; + } + + /// + /// Gets the ECDSA signature + /// + /// + /// + private string GetECDSASignature(byte[] dataToSign) + { + {{#net60OrLater}} + if (!File.Exists(KeyFilePath)) + throw new Exception("key file path does not exist."); + + var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var keyStr = File.ReadAllText(KeyFilePath); + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + + string ptrToStringUni = Marshal.PtrToStringUni(unmanagedString) ?? throw new NullReferenceException(); + + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(ptrToStringUni), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + else + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; + {{/net60OrLater}} + {{^net60OrLater}} + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); + {{/net60OrLater}} + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default length for ECDSA code signing bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + rBytes.Add(signedBytes[i]); + + for (int i = 32; i < 64; i++) + sBytes.Add(signedBytes[i]); + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r length, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider{{nrt?}} GetRSAProviderFromPemFile(String pemfile, SecureString{{nrt?}} keyPassPhrase = null) + { + const String pempubheader = "-----BEGIN PUBLIC KEY-----"; + const String pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[]{{nrt?}} pemkey = null; + + if (!File.Exists(pemfile)) + throw new Exception("private key file does not exist."); + + string pemstr = File.ReadAllText(pemfile).Trim(); + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + isPrivateKeyFile = false; + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPhrase); + + if (pemkey == null) + return null; + + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[]{{nrt?}} ConvertPrivateKeyToBytes(String instr, SecureString{{nrt?}} keyPassPhrase = null) + { + const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; + String pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + return null; + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + String pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine(){{nrt!}}.StartsWith("Proc-Type: 4,ENCRYPTED")) // TODO: what do we do here if ReadLine is null? + return null; + + String saltline = str.ReadLine(){{nrt!}}; // TODO: what do we do here if ReadLine is null? + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + return null; + + String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + + if (!(str.ReadLine() == "")) + return null; + + //------ remaining b64 data is encrypted RSA key ---- + String encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 format + return null; + } + + // TODO: what do we do here if keyPassPhrase is null? + byte[] deskey = GetEncryptedKey(salt, keyPassPhrase{{nrt!}}, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + return null; + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[]{{nrt?}} rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + + return rsakey; + } + } + + private RSACryptoServiceProvider{{nrt?}} DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) + return null; + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + return 0; + + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); // data size in next byte + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + count = bt; // we already have the data size + + while (binr.ReadByte() == 0x00) + //remove high order zeros in data + count -= 1; + + binr.BaseStream.Seek(-1, SeekOrigin.Current); + + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- concatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = MD5.Create(); + byte[]{{nrt?}} result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + result = data00; //initialize + else + { + Array.Copy(result{{nrt!}}, hashtarget, result{{nrt!}}.Length); // TODO: what do we do if result is null here? + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + result = md5.ComputeHash(result); + + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result{{nrt!}}, 0, result{{nrt!}}.Length); // TODO: what do we do if result is null here? + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[]{{nrt?}} DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// + private PrivateKeyType GetKeyType(string keyFilePath) + { + if (!File.Exists(keyFilePath)) + throw new Exception("Key file path does not exist."); + + var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + var ecPrivateKeyFooter = "END EC PRIVATE KEY"; + var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + var rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + var keyType = PrivateKeyType.None; + var key = File.ReadAllLines(keyFilePath); + + if (key[0].ToString().Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + keyType = PrivateKeyType.RSA; + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + keyType = PrivateKeyType.ECDSA; + + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + /* this type of key can hold many type different types of private key, but here due lack of pem header + Considering this as EC key + */ + //TODO :- update the key based on oid + keyType = PrivateKeyType.ECDSA; + } + else + throw new Exception("Either the key is invalid or key is not supported"); + + return keyType; + } + } +} diff --git a/generation/templates/libraries/generichost/HttpSigningToken.mustache b/generation/templates/libraries/generichost/HttpSigningToken.mustache new file mode 100644 index 00000000..f9c0167a --- /dev/null +++ b/generation/templates/libraries/generichost/HttpSigningToken.mustache @@ -0,0 +1,45 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed from an HttpSigningConfiguration + /// + {{>visibility}} class HttpSignatureToken : TokenBase + { + private HttpSigningConfiguration _configuration; + + /// + /// Constructs an HttpSignatureToken object. + /// + /// + /// + public HttpSignatureToken(HttpSigningConfiguration configuration, TimeSpan? timeout = null) : base(timeout) + { + _configuration = configuration; + } + + /// + /// Places the token in the header. + /// + /// + /// + /// + public void UseInHeader(System.Net.Http.HttpRequestMessage request, string requestBody, CancellationToken cancellationToken = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) + { + var signedHeaders = _configuration.GetHttpSignedHeader(request, requestBody, cancellationToken); + + foreach (var signedHeader in signedHeaders) + request.Headers.Add(signedHeader.Key, signedHeader.Value); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/IApi.mustache b/generation/templates/libraries/generichost/IApi.mustache new file mode 100644 index 00000000..af31cffe --- /dev/null +++ b/generation/templates/libraries/generichost/IApi.mustache @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace {{packageName}}.{{apiPackage}} +{ + /// + /// Any Api client + /// + {{>visibility}} interface {{interfacePrefix}}Api + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/IHostBuilderExtensions.mustache b/generation/templates/libraries/generichost/IHostBuilderExtensions.mustache new file mode 100644 index 00000000..948f0664 --- /dev/null +++ b/generation/templates/libraries/generichost/IHostBuilderExtensions.mustache @@ -0,0 +1,55 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using {{packageName}}.{{clientPackage}}; + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + {{>visibility}} static class IHostBuilderExtensions + { + {{^hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + IServiceCollectionExtensions.Add{{apiName}}(services, config); + }); + + return builder; + } + + {{/hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder Configure{{apiName}}(this IHostBuilder builder, Action options) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.Add{{apiName}}(services, config); + }); + + return builder; + } + } +} diff --git a/generation/templates/libraries/generichost/IHttpClientBuilderExtensions.mustache b/generation/templates/libraries/generichost/IHttpClientBuilderExtensions.mustache new file mode 100644 index 00000000..053c0226 --- /dev/null +++ b/generation/templates/libraries/generichost/IHttpClientBuilderExtensions.mustache @@ -0,0 +1,75 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}} +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly;{{/supportsRetry}} + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + {{>visibility}} static class IHttpClientBuilderExtensions + { + {{#supportsRetry}} + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + {{/supportsRetry}} + } +} diff --git a/generation/templates/libraries/generichost/IServiceCollectionExtensions.mustache b/generation/templates/libraries/generichost/IServiceCollectionExtensions.mustache new file mode 100644 index 00000000..14184ac4 --- /dev/null +++ b/generation/templates/libraries/generichost/IServiceCollectionExtensions.mustache @@ -0,0 +1,69 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{clientPackage}}; + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + {{>visibility}} static class IServiceCollectionExtensions + { + {{^hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + public static void Add{{apiName}}(this IServiceCollection services) + { + HostConfiguration config = new{{^net70OrLater}} HostConfiguration{{/net70OrLater}}(services); + Add{{apiName}}(services, config); + } + + {{/hasAuthMethods}} + /// + /// Add the api to your host builder. + /// + /// + /// + public static void Add{{apiName}}(this IServiceCollection services, Action options) + { + HostConfiguration config = new{{^net70OrLater}} HostConfiguration{{/net70OrLater}}(services); + options(config); + Add{{apiName}}(services, config); + } + + internal static void Add{{apiName}}(IServiceCollection services, HostConfiguration host) + { + if (!host.HttpClientsAdded) + host.Add{{apiName}}HttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/generation/templates/libraries/generichost/ImplementsIEquatable.mustache b/generation/templates/libraries/generichost/ImplementsIEquatable.mustache new file mode 100644 index 00000000..dd576dd0 --- /dev/null +++ b/generation/templates/libraries/generichost/ImplementsIEquatable.mustache @@ -0,0 +1 @@ +{{#equatable}}{{#readOnlyVars}}{{#-first}}IEquatable<{{classname}}{{nrt?}}> {{/-first}}{{/readOnlyVars}}{{/equatable}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ImplementsValidatable.mustache b/generation/templates/libraries/generichost/ImplementsValidatable.mustache new file mode 100644 index 00000000..7c3f0e02 --- /dev/null +++ b/generation/templates/libraries/generichost/ImplementsValidatable.mustache @@ -0,0 +1 @@ +{{#validatable}}IValidatableObject {{/validatable}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/JsonConverter.mustache b/generation/templates/libraries/generichost/JsonConverter.mustache new file mode 100644 index 00000000..189acfd7 --- /dev/null +++ b/generation/templates/libraries/generichost/JsonConverter.mustache @@ -0,0 +1,648 @@ + /// + /// A Json converter for type + /// + {{>visibility}} class {{classname}}JsonConverter : JsonConverter<{{classname}}> + { + {{#allVars}} + {{#isDateTime}} + /// + /// The format to use to serialize {{name}} + /// + public static string {{name}}Format { get; set; } = "{{{dateTimeFormat}}}"; + + {{/isDateTime}} + {{#isDate}} + /// + /// The format to use to serialize {{name}} + /// + public static string {{name}}Format { get; set; } = "{{{dateFormat}}}"; + + {{/isDate}} + {{/allVars}} + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override {{classname}} Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + {{#allVars}} + Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + {{/-last}} + {{/allVars}} + {{#discriminator}} + {{#children}} + {{#-first}} + string{{nrt?}} discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "{{discriminator.propertyBaseName}}"); + + {{/-first}} + if (discriminator != null && discriminator.Equals("{{name}}")) + return JsonSerializer.Deserialize<{{{name}}}>(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + {{/children}} + {{/discriminator}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#mappedModels}} + {{#model}} + {{^vendorExtensions.x-duplicated-data-type}} + {{classname}}{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} = null; + {{#-last}} + + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/model}} + {{/mappedModels}} + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string{{nrt?}} localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName{{nrt?}}.Equals("{{propertyBaseName}}"){{#nrt}} ?? false{{/nrt}}) + { + string{{nrt?}} discriminator = utf8JsonReaderDiscriminator.GetString(); + {{#mappedModels}} + if (discriminator{{nrt?}}.Equals("{{mappingName}}"){{#nrt}} ?? false{{/nrt}}) + { + Utf8JsonReader utf8JsonReader{{model.classname}} = utf8JsonReader; + {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} = JsonSerializer.Deserialize<{{{model.classname}}}>(ref utf8JsonReader{{model.classname}}, jsonSerializerOptions); + } + {{/mappedModels}} + } + } + } + + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + {{#oneOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/oneOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderAnyOf = utf8JsonReader; + while (utf8JsonReaderAnyOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (utf8JsonReaderAnyOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderAnyOf.CurrentDepth - 1) + { + {{#anyOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/anyOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + + {{/composedSchemas}} + {{/model.discriminator}} + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string{{nrt?}} localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + {{#allVars}} + case "{{baseName}}": + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetString(){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetBoolean()); + {{/isBoolean}} + {{#isNumeric}} + {{^isEnum}} + {{#isDouble}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetDouble()); + {{/isDouble}} + {{#isDecimal}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetDecimal()); + {{/isDecimal}} + {{#isFloat}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}(float)utf8JsonReader.GetDouble()); + {{/isFloat}} + {{#isLong}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int64()); + {{/isLong}} + {{^isLong}} + {{^isFloat}} + {{^isDecimal}} + {{^isDouble}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isDouble}} + {{/isDecimal}} + {{/isFloat}} + {{/isLong}} + {{/isEnum}} + {{/isNumeric}} + {{#isDate}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{#supportsDateOnly}}DateOnly{{/supportsDateOnly}}{{^supportsDateOnly}}DateTime{{/supportsDateOnly}}{{#isNullable}}?{{/isNullable}}>(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDate}} + {{#isDateTime}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDateTime}} + {{#isEnum}} + {{^isMap}} + {{#isNumeric}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}})utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isNumeric}} + {{^isNumeric}} + string{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = utf8JsonReader.GetString(); + {{^isInnerEnum}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isInnerEnum}} + {{#isInnerEnum}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{classname}}.{{{datatypeWithEnum}}}FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetGuid()); + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + if (utf8JsonReader.TokenType != JsonTokenType.Null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref utf8JsonReader, jsonSerializerOptions){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + break; + {{/allVars}} + default: + break; + } + } + } + + {{#allVars}} + {{#required}} + if (!{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.IsSet) + throw new ArgumentException("Property is required for class {{classname}}.", nameof({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}})); + + {{/required}} + {{/allVars}} + {{#allVars}} + {{^isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.IsSet && {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.Value == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}), "Property is not nullable for class {{classname}}."); + + {{/isNullable}} + {{/allVars}} + {{^vendorExtensions.x-duplicated-data-type}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#mappedModels}} + if ({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/mappedModels}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^composedSchemas.oneOf}} + {{^required}} + {{#model.composedSchemas.anyOf}} + Option<{{baseType}}{{>NullConditionalProperty}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} == null + ? default + : new Option<{{baseType}}{{>NullConditionalProperty}}>({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{/model.composedSchemas.anyOf}} + {{#-last}} + + {{/-last}} + {{/required}} + return new {{classname}}({{#lambda.joinWithComma}}{{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue{{#required}}.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/required}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + {{/composedSchemas.oneOf}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}ParsedValue{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{/vendorExtensions.x-duplicated-data-type}} + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/oneOf}} + {{/composedSchemas}} + {{/model.discriminator}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimLineBreaks}} + {{#lambda.copy}} + {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copy}} + {{#discriminator}} + {{#children}} + if ({{#lambda.pasteLine}}{{/lambda.pasteLine}} is {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}){ + JsonSerializer.Serialize<{{{name}}}>(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + return; + } + + {{/children}} + {{/discriminator}} + writer.WriteStartObject(); + + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{baseType}}JsonConverter {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}} = ({{baseType}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.GetType())); + {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}}.WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#anyOf}} + if ({{#lambda.joinWithAmpersand}}{{^required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet {{/required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}} != null{{/lambda.joinWithAmpersand}}) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{datatypeWithEnum}}JsonConverter {{datatypeWithEnum}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}.GetType())); + {{datatypeWithEnum}}JsonConverter.WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/anyOf}} + {{/composedSchemas}} + {{/model.discriminator}} + WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + writer.WriteEndObject(); + {{/lambda.trimLineBreaks}} + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + {{#allVars}} + {{^isDiscriminator}} + {{^isNullable}} + {{#vendorExtensions.x-is-reference-type}} + if ({{^required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet && {{/required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}), "Property is required for class {{classname}}."); + + {{/vendorExtensions.x-is-reference-type}} + {{/isNullable}} + {{/isDiscriminator}} + {{/allVars}} + {{#allVars}} + {{#isDiscriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + writer.WriteString("{{baseName}}", {{^isEnum}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{/isEnum}}{{#isNew}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{{datatypeWithEnum}}}ToJsonValue{{/isInnerEnum}}{{^isInnerEnum}}{{{datatypeWithEnum}}}ValueConverter.ToJsonValue{{/isInnerEnum}}({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}.Value{{/required}}){{/isEnum}}{{/isNew}}); + + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/isDiscriminator}} + {{^isDiscriminator}} + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#lambda.copy}} + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isBoolean}} + {{^isEnum}} + {{#isNumeric}} + {{#lambda.copy}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isNumeric}} + {{/isEnum}} + {{#isDate}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isDate}} + {{#isDateTime}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isDateTime}} + {{#isEnum}} + {{#isNumeric}} + {{#lambda.copy}} + writer.WriteNumber("{{baseName}}", {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}})); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isNumeric}} + {{^isMap}} + {{^isNumeric}} + {{#isInnerEnum}} + {{#isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isNullable}} + {{/isInnerEnum}} + {{^isInnerEnum}} + {{#lambda.copy}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copy}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} == null) + writer.WriteNull("{{baseName}}"); + else + { + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.Value); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + if ({{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue != null){{! we cant use name here because enumVar also has a name property, so use the paste lambda instead }} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + {{/isString}} + {{^isString}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{^isNumeric}} + writer.WriteString("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue); + {{/isNumeric}} + {{#isNumeric}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isNumeric}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{/isNullable}} + + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option{{nrt!}}.Value != null) + { + var {{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + var {{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}RawValue); + } + {{/isNullable}} + {{/required}} + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + {{/isNullable}} + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isNullable}} + {{/required}} + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + {{/isDiscriminator}} + {{/allVars}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + } \ No newline at end of file diff --git a/generation/templates/libraries/generichost/JsonSerializerOptionsProvider.mustache b/generation/templates/libraries/generichost/JsonSerializerOptionsProvider.mustache new file mode 100644 index 00000000..93f80540 --- /dev/null +++ b/generation/templates/libraries/generichost/JsonSerializerOptionsProvider.mustache @@ -0,0 +1,29 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Text.Json; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides the JsonSerializerOptions + /// + {{>visibility}} class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ModelBaseSignature.mustache b/generation/templates/libraries/generichost/ModelBaseSignature.mustache new file mode 100644 index 00000000..909a68e3 --- /dev/null +++ b/generation/templates/libraries/generichost/ModelBaseSignature.mustache @@ -0,0 +1 @@ +{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{parent}}{{/lambda.camelcase_sanitize_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#isInherited}}{{^isNew}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{/isNew}}{{#isNew}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{{datatypeWithEnum}}}ToJsonValue{{/isInnerEnum}}{{^isInnerEnum}}{{{datatypeWithEnum}}}ValueConverter.ToJsonValue{{/isInnerEnum}}({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{^required}}.Value{{/required}}){{/isEnum}}{{^isEnum}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.ToString(){{/isEnum}}{{/isNew}} {{/isInherited}}{{/isDiscriminator}}{{/allVars}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ModelSignature.mustache b/generation/templates/libraries/generichost/ModelSignature.mustache new file mode 100644 index 00000000..39aa11f8 --- /dev/null +++ b/generation/templates/libraries/generichost/ModelSignature.mustache @@ -0,0 +1 @@ +{{#model.allVars}}{{^isDiscriminator}}{{^required}}Option<{{/required}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}{{#defaultValue}} = {{^required}}default{{/required}}{{#required}}{{^isDateTime}}{{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}{{{.}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/required}}{{/defaultValue}}{{^defaultValue}}{{#lambda.first}}{{#isNullable}} = default {{/isNullable}}{{^required}} = default {{/required}}{{/lambda.first}}{{/defaultValue}} {{/isDiscriminator}}{{/model.allVars}} diff --git a/generation/templates/libraries/generichost/OAuthToken.mustache b/generation/templates/libraries/generichost/OAuthToken.mustache new file mode 100644 index 00000000..f450c3d0 --- /dev/null +++ b/generation/templates/libraries/generichost/OAuthToken.mustache @@ -0,0 +1,41 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed with OAuth. + /// + {{>visibility}} class OAuthToken : TokenBase + { + private string _raw; + + /// + /// Consturcts an OAuthToken object. + /// + /// + /// + public OAuthToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/OnDeserializationError.mustache b/generation/templates/libraries/generichost/OnDeserializationError.mustache new file mode 100644 index 00000000..ff83a507 --- /dev/null +++ b/generation/templates/libraries/generichost/OnDeserializationError.mustache @@ -0,0 +1,2 @@ +if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); \ No newline at end of file diff --git a/generation/templates/libraries/generichost/OnErrorDefaultImplementation.mustache b/generation/templates/libraries/generichost/OnErrorDefaultImplementation.mustache new file mode 100644 index 00000000..7af8e076 --- /dev/null +++ b/generation/templates/libraries/generichost/OnErrorDefaultImplementation.mustache @@ -0,0 +1,2 @@ + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); \ No newline at end of file diff --git a/generation/templates/libraries/generichost/OperationSignature.mustache b/generation/templates/libraries/generichost/OperationSignature.mustache new file mode 100644 index 00000000..83076f2b --- /dev/null +++ b/generation/templates/libraries/generichost/OperationSignature.mustache @@ -0,0 +1 @@ +{{#lambda.joinWithComma}}{{#allParams}}{{#required}}{{{dataType}}}{{>NullConditionalParameter}}{{/required}}{{^required}}Option<{{{dataType}}}{{>NullConditionalParameter}}>{{/required}} {{paramName}}{{#notRequiredOrIsNullable}} = default{{/notRequiredOrIsNullable}} {{/allParams}}System.Threading.CancellationToken cancellationToken = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}{{/lambda.joinWithComma}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/Option.mustache b/generation/templates/libraries/generichost/Option.mustache new file mode 100644 index 00000000..eed49143 --- /dev/null +++ b/generation/templates/libraries/generichost/Option.mustache @@ -0,0 +1,47 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/OptionProperty.mustache b/generation/templates/libraries/generichost/OptionProperty.mustache new file mode 100644 index 00000000..d7504188 --- /dev/null +++ b/generation/templates/libraries/generichost/OptionProperty.mustache @@ -0,0 +1 @@ +new Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>( \ No newline at end of file diff --git a/generation/templates/libraries/generichost/README.client.mustache b/generation/templates/libraries/generichost/README.client.mustache new file mode 100644 index 00000000..371b9daa --- /dev/null +++ b/generation/templates/libraries/generichost/README.client.mustache @@ -0,0 +1,245 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName={{apiName}}', + 'targetFramework={{targetFramework}}', + 'validatable={{validatable}}', + 'nullableReferenceTypes={{nullableReferenceTypes}}', + 'hideGenerationTimestamp={{hideGenerationTimestamp}}', + 'packageVersion={{packageVersion}}', + 'packageAuthors={{packageAuthors}}', + 'packageCompany={{packageCompany}}', + 'packageCopyright={{packageCopyright}}', + 'packageDescription={{packageDescription}}',{{#licenseId}} + 'licenseId={{.}}',{{/licenseId}} + 'packageName={{packageName}}', + 'packageTags={{packageTags}}', + 'packageTitle={{packageTitle}}' +) -join "," + +$global = @( + 'apiDocs={{generateApiDocs}}', + 'modelDocs={{generateModelDocs}}', + 'apiTests={{generateApiTests}}', + 'modelTests={{generateModelTests}}' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "{{gitHost}}" ` + --git-repo-id "{{gitRepoId}}" ` + --git-user-id "{{gitUserId}}" ` + --release-note "{{releaseNote}}" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.Api; +using {{packageName}}.Client; +using {{packageName}}.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build();{{#apiInfo}}{{#apis}}{{#-first}} + var api = host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#operations}} + {{#-first}} + {{#operation}} + {{#-first}} + {{operationId}}ApiResponse apiResponse = await api.{{operationId}}Async("todo"); + {{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}} model = apiResponse.Ok(); + {{/-first}} + {{/operation}} + {{/-first}} + {{/operations}} + {{/-first}} + {{/apis}} + {{/apiInfo}} + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .Configure{{apiName}}((context, options) => + { + {{#authMethods}} + {{#-first}} + // the type of token here depends on the api security specifications + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + {{/-first}} + {{/authMethods}} + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.Add{{apiName}}HttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace {{packageName}}.Rest.DefaultApi. + Or provide your own class by using the generic Configure{{apiName}} method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later{{#supportsRetry}} +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later{{/supportsRetry}}{{#useCompareNetObjects}} +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later{{/useCompareNetObjects}}{{#validatable}} +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later{{/validatable}}{{#apiDocs}} + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | -------------{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}{{/apiDocs}}{{#modelDocs}} + + +## Documentation for Models + +{{#modelPackage}}{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md){{/model}}{{/models}}{{/modelPackage}} +{{^modelPackage}}No model defined in this package{{/modelPackage}}{{/modelDocs}} + + +## Documentation for Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}} +- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}} +- **Type**: Bearer Authentication +{{/isBasicBearer}} +{{#isHttpSignature}} +- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isOAuth}} +- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}}{{#scopes}} +- {{scope}}: {{description}}{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Build +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: {{generatorClass}} + +## Api Information +- appName: {{appName}} +- appVersion: {{appVersion}} +- appDescription: {{appDescription}} + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: {{generateAliasAsModel}} +- supportingFiles: {{supportingFiles}} +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: {{generateApiDocs}} +- modelDocs: {{generateModelDocs}} +- apiTests: {{generateApiTests}} +- modelTests: {{generateModelTests}} + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: {{allowUnicodeIdentifiers}} +- apiName: {{apiName}} +- caseInsensitiveResponseHeaders: {{caseInsensitiveResponseHeaders}} +- conditionalSerialization: {{conditionalSerialization}} +- disallowAdditionalPropertiesIfNotPresent: {{disallowAdditionalPropertiesIfNotPresent}} +- gitHost: {{gitHost}} +- gitRepoId: {{gitRepoId}} +- gitUserId: {{gitUserId}} +- hideGenerationTimestamp: {{hideGenerationTimestamp}} +- interfacePrefix: {{interfacePrefix}} +- library: {{library}} +- licenseId: {{licenseId}} +- modelPropertyNaming: {{modelPropertyNaming}} +- netCoreProjectFile: {{netCoreProjectFile}} +- nonPublicApi: {{nonPublicApi}} +- nullableReferenceTypes: {{nullableReferenceTypes}} +- optionalAssemblyInfo: {{optionalAssemblyInfo}} +- optionalEmitDefaultValues: {{optionalEmitDefaultValues}} +- optionalMethodArgument: {{optionalMethodArgument}} +- optionalProjectFile: {{optionalProjectFile}} +- packageAuthors: {{packageAuthors}} +- packageCompany: {{packageCompany}} +- packageCopyright: {{packageCopyright}} +- packageDescription: {{packageDescription}} +- packageGuid: {{packageGuid}} +- packageName: {{packageName}} +- packageTags: {{packageTags}} +- packageTitle: {{packageTitle}} +- packageVersion: {{packageVersion}} +- releaseNote: {{releaseNote}} +- returnICollection: {{returnICollection}} +- sortParamsByRequiredFlag: {{sortParamsByRequiredFlag}} +- sourceFolder: {{sourceFolder}} +- targetFramework: {{targetFramework}} +- useCollection: {{useCollection}} +- useDateTimeOffset: {{useDateTimeOffset}} +- useOneOfDiscriminatorLookup: {{useOneOfDiscriminatorLookup}} +- validatable: {{validatable}}{{#infoUrl}} +For more information, please visit [{{{.}}}]({{{.}}}){{/infoUrl}} + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. diff --git a/generation/templates/libraries/generichost/README.solution.mustache b/generation/templates/libraries/generichost/README.solution.mustache new file mode 100644 index 00000000..f9c1c7f7 --- /dev/null +++ b/generation/templates/libraries/generichost/README.solution.mustache @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/generation/templates/libraries/generichost/README.test.mustache b/generation/templates/libraries/generichost/README.test.mustache new file mode 100644 index 00000000..e69de29b diff --git a/generation/templates/libraries/generichost/RateLimitProvider`1.mustache b/generation/templates/libraries/generichost/RateLimitProvider`1.mustache new file mode 100644 index 00000000..4e44b3fd --- /dev/null +++ b/generation/templates/libraries/generichost/RateLimitProvider`1.mustache @@ -0,0 +1,76 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Channels; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + {{>visibility}} class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Dictionary> AvailableTokens { get; } = new{{^net70OrLater}} Dictionary>{{/net70OrLater}}(); + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + {{#lambda.copy}} + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + {{/lambda.copy}} + {{#hasApiKeyMethods}} + if (container is TokenContainer apiKeyTokenContainer) + { + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); + + foreach (string header in headers) + { + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(header, Channel.CreateBounded(options)); + } + } + else + { + {{#lambda.indent1}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/lambda.indent1}} + } + {{/hasApiKeyMethods}} + {{^hasApiKeyMethods}} + {{#lambda.pasteLine}}{{/lambda.pasteLine}} + {{/hasApiKeyMethods}} + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) + { + if (!AvailableTokens.TryGetValue(header, out Channel{{nrt?}} tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } + } +} diff --git a/generation/templates/libraries/generichost/SourceGenerationContext.mustache b/generation/templates/libraries/generichost/SourceGenerationContext.mustache new file mode 100644 index 00000000..b1798c98 --- /dev/null +++ b/generation/templates/libraries/generichost/SourceGenerationContext.mustache @@ -0,0 +1,9 @@ +{{#useSourceGeneration}} + + /// + /// The {{classname}}SerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof({{classname}}))] + {{>visibility}} partial class {{classname}}SerializationContext : JsonSerializerContext { } +{{/useSourceGeneration}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/TokenBase.mustache b/generation/templates/libraries/generichost/TokenBase.mustache new file mode 100644 index 00000000..05f06b4a --- /dev/null +++ b/generation/templates/libraries/generichost/TokenBase.mustache @@ -0,0 +1,73 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// The base for all tokens. + /// + {{>visibility}} abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler{{nrt?}} TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object{{nrt?}} sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/TokenContainer`1.mustache b/generation/templates/libraries/generichost/TokenContainer`1.mustache new file mode 100644 index 00000000..3e8f1b15 --- /dev/null +++ b/generation/templates/libraries/generichost/TokenContainer`1.mustache @@ -0,0 +1,39 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Linq; +using System.Collections.Generic; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A container for a collection of tokens. + /// + /// + {{>visibility}} sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/TokenProvider`1.mustache b/generation/templates/libraries/generichost/TokenProvider`1.mustache new file mode 100644 index 00000000..52972546 --- /dev/null +++ b/generation/templates/libraries/generichost/TokenProvider`1.mustache @@ -0,0 +1,38 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Collections.Generic; +using {{packageName}}.{{clientPackage}}; + +namespace {{packageName}} +{ + /// + /// A class which will provide tokens. + /// + {{>visibility}} abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/ValidateRegex.mustache b/generation/templates/libraries/generichost/ValidateRegex.mustache new file mode 100644 index 00000000..78aba8fb --- /dev/null +++ b/generation/templates/libraries/generichost/ValidateRegex.mustache @@ -0,0 +1,7 @@ +// {{{name}}} ({{{dataType}}}) pattern +Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); +{{#lambda.copy}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null && {{/lambda.copy}} +if ({{#lambda.first}}{{^required}}{{#lambda.pasteLine}}{{/lambda.pasteLine}} {{/required}}{{#isNullable}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/isNullable}}{{/lambda.first}}!regex{{{name}}}.Match(this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}}{{#isUuid}}.ToString(){{#lambda.first}}{{^required}}{{nrt!}} {{/required}}{{#isNullable}}! {{/isNullable}}{{/lambda.first}}{{/isUuid}}).Success) +{ + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/WriteProperty.mustache b/generation/templates/libraries/generichost/WriteProperty.mustache new file mode 100644 index 00000000..99659ac2 --- /dev/null +++ b/generation/templates/libraries/generichost/WriteProperty.mustache @@ -0,0 +1,9 @@ +{{#required}} +{{>WritePropertyHelper}} +{{/required}} +{{^required}} +if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet) + {{#lambda.indent1}} + {{>WritePropertyHelper}} + {{/lambda.indent1}} +{{/required}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/WritePropertyHelper.mustache b/generation/templates/libraries/generichost/WritePropertyHelper.mustache new file mode 100644 index 00000000..183946cf --- /dev/null +++ b/generation/templates/libraries/generichost/WritePropertyHelper.mustache @@ -0,0 +1,9 @@ +{{#isNullable}} +if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}} != null) + {{#lambda.pasteLine}}{{/lambda.pasteLine}} +else + writer.WriteNull("{{baseName}}"); +{{/isNullable}} +{{^isNullable}} +{{#lambda.pasteLine}}{{/lambda.pasteLine}} +{{/isNullable}} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/api.mustache b/generation/templates/libraries/generichost/api.mustache new file mode 100644 index 00000000..eccb02d5 --- /dev/null +++ b/generation/templates/libraries/generichost/api.mustache @@ -0,0 +1,788 @@ +{{#lambda.trimLineBreaks}} +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +{{#net80OrLater}} +{{#lambda.uniqueLines}} +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-set-cookie}} +using System.Linq; +{{/vendorExtensions.x-set-cookie}} +{{/operation}} +{{/operations}} +{{/lambda.uniqueLines}} +{{/net80OrLater}} +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using {{packageName}}.{{clientPackage}}; +{{#hasImport}} +using {{packageName}}.{{modelPackage}}; +{{/hasImport}} +{{^netStandard}} +using System.Diagnostics.CodeAnalysis; +{{/netStandard}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : IApi + { + /// + /// The class containing the events + /// + {{classname}}Events Events { get; } + + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// <> + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + Task<{{interfacePrefix}}{{operationId}}ApiResponse> {{operationId}}Async({{>OperationSignature}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// <{{nrt?}}> + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + Task<{{interfacePrefix}}{{operationId}}ApiResponse{{nrt?}}> {{operationId}}OrDefaultAsync({{>OperationSignature}}); + {{^-last}} + + {{/-last}} + {{/operation}} + } + {{#operation}} + {{#responses}} + {{#-first}} + + /// + /// The + /// + {{>visibility}} interface {{interfacePrefix}}{{operationId}}ApiResponse : {{#lambda.joinWithComma}}{{packageName}}.{{clientPackage}}.{{interfacePrefix}}ApiResponse {{#responses}}{{#dataType}}{{interfacePrefix}}{{vendorExtensions.x-http-status}}<{{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{/dataType}}{{/responses}}{{/lambda.joinWithComma}} + { + {{#responses}} + {{#vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is the default response type + /// + /// + bool Is{{vendorExtensions.x-http-status}} { get; } + {{/vendorExtensions.x-http-status-is-default}} + {{^vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}} + /// + /// + bool Is{{vendorExtensions.x-http-status}} { get; } + {{/vendorExtensions.x-http-status-is-default}} + {{^-last}} + + {{/-last}} + {{/responses}} + } + {{/-first}} + {{/responses}} + {{/operation}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} class {{classname}}Events + { + {{#lambda.trimTrailingWithNewLine}} + {{#operation}} + /// + /// The event raised after the server response + /// + public event EventHandler{{nrt?}} On{{operationId}}; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler{{nrt?}} OnError{{operationId}}; + + internal void ExecuteOn{{operationId}}({{classname}}.{{operationId}}ApiResponse apiResponse) + { + On{{operationId}}?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnError{{operationId}}(Exception exception) + { + OnError{{operationId}}?.Invoke(this, new ExceptionEventArgs(exception)); + } + + {{/operation}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} sealed partial class {{classname}} : {{interfacePrefix}}{{classname}} + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger<{{classname}}> Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public {{classname}}Events Events { get; }{{#hasApiKeyMethods}} + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; }{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; }{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; }{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; }{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; }{{/hasOAuthMethods}} + + {{#net80OrLater}} + {{#lambda.unique}} + {{#operation}} + {{#vendorExtensions.x-set-cookie}} + /// + /// The token cookie container + /// + public {{packageName}}.{{clientPackage}}.CookieContainer CookieContainer { get; } + + {{/vendorExtensions.x-set-cookie}} + {{/operation}} + {{/lambda.unique}} + {{/net80OrLater}} + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(ILogger<{{classname}}> logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#hasApiKeyMethods}}, + TokenProvider apiKeyProvider{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}, + TokenProvider bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}}, + TokenProvider basicTokenProvider{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}}, + TokenProvider httpSignatureTokenProvider{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}, + TokenProvider oauthTokenProvider{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}}, + {{packageName}}.{{clientPackage}}.CookieContainer cookieContainer{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}}) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger<{{classname}}>(); + HttpClient = httpClient; + Events = {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}};{{#hasApiKeyMethods}} + ApiKeyProvider = apiKeyProvider;{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} + BearerTokenProvider = bearerTokenProvider;{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} + BasicTokenProvider = basicTokenProvider;{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} + HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} + OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}} + CookieContainer = cookieContainer;{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}} + } + {{#operation}} + + {{#allParams}} + {{#-first}} + partial void Format{{operationId}}({{#allParams}}{{#isPrimitiveType}}ref {{/isPrimitiveType}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + + {{/-first}} + {{/allParams}} + {{#vendorExtensions.x-has-not-nullable-reference-types}} + /// + /// Validates the request parameters + /// + {{#vendorExtensions.x-not-nullable-reference-types}} + /// + {{/vendorExtensions.x-not-nullable-reference-types}} + /// + private void Validate{{operationId}}({{#vendorExtensions.x-not-nullable-reference-types}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-not-nullable-reference-types}}) + { + {{#lambda.trimTrailingWithNewLine}} + {{#vendorExtensions.x-not-nullable-reference-types}} + {{#required}} + {{^vendorExtensions.x-is-value-type}} + if ({{paramName}} == null) + throw new ArgumentNullException(nameof({{paramName}})); + + {{/vendorExtensions.x-is-value-type}} + {{/required}} + {{^required}} + {{^vendorExtensions.x-is-value-type}} + if ({{paramName}}.IsSet && {{paramName}}.Value == null) + throw new ArgumentNullException(nameof({{paramName}})); + + {{/vendorExtensions.x-is-value-type}} + {{/required}} + {{/vendorExtensions.x-not-nullable-reference-types}} + {{/lambda.trimTrailingWithNewLine}} + } + + {{/vendorExtensions.x-has-not-nullable-reference-types}} + /// + /// Processes the server response + /// + /// + {{#allParams}} + /// + {{/allParams}} + private void After{{operationId}}DefaultImplementation({{#lambda.joinWithComma}}{{interfacePrefix}}{{operationId}}ApiResponse apiResponseLocalVar {{#allParams}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} {{/allParams}}{{/lambda.joinWithComma}}) + { + bool suppressDefaultLog = false; + After{{operationId}}({{#lambda.joinWithComma}}ref suppressDefaultLog apiResponseLocalVar {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); +{{>AfterOperationDefaultImplementation}} + } + + /// + /// Processes the server response + /// + /// + /// + {{#allParams}} + /// + {{/allParams}} + partial void After{{operationId}}({{#lambda.joinWithComma}}ref bool suppressDefaultLog {{interfacePrefix}}{{operationId}}ApiResponse apiResponseLocalVar {{#allParams}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + {{#allParams}} + /// + {{/allParams}} + private void OnError{{operationId}}DefaultImplementation({{#lambda.joinWithComma}}Exception exception string pathFormat string path {{#allParams}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} {{/allParams}}{{/lambda.joinWithComma}}) + { + bool suppressDefaultLog = false; + OnError{{operationId}}({{#lambda.joinWithComma}}ref suppressDefaultLog exception pathFormat path {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); +{{>OnErrorDefaultImplementation}} + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + {{#allParams}} + /// + {{/allParams}} + partial void OnError{{operationId}}({{#lambda.joinWithComma}}ref bool suppressDefaultLog Exception exception string pathFormat string path {{#allParams}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); + + /// + /// {{summary}} {{notes}} + /// + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// <> + public async Task<{{interfacePrefix}}{{operationId}}ApiResponse{{nrt?}}> {{operationId}}OrDefaultAsync({{>OperationSignature}}) + { + try + { + return await {{operationId}}Async({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// <> + public async Task<{{interfacePrefix}}{{operationId}}ApiResponse> {{operationId}}Async({{>OperationSignature}}) + { + {{#lambda.trimLineBreaks}} + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + {{#vendorExtensions.x-has-not-nullable-reference-types}} + Validate{{operationId}}({{#vendorExtensions.x-not-nullable-reference-types}}{{paramName}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-not-nullable-reference-types}}); + + {{/vendorExtensions.x-has-not-nullable-reference-types}} + {{#allParams}} + {{#-first}} + Format{{operationId}}({{#allParams}}{{#isPrimitiveType}}ref {{/isPrimitiveType}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + + {{/-first}} + {{/allParams}} + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + {{^servers}} + uriBuilderLocalVar.Host = HttpClient.BaseAddress{{nrt!}}.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "{{path}}"; + {{/servers}} + {{#servers}} + {{#-first}} + Uri urlLocalVar = httpRequestMessageLocalVar.RequestUri = new Uri("{{url}}"); + uriBuilderLocalVar.Host = urlLocalVar.Authority; + uriBuilderLocalVar.Scheme = urlLocalVar.Scheme; + uriBuilderLocalVar.Path = urlLocalVar.AbsolutePath; + {{/-first}} + {{/servers}} + {{#constantParams}} + {{#isPathParam}} + // Set client side default value of Path Param "{{baseName}}". + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString(ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}}))); // Constant path parameter + {{/isPathParam}} + {{/constantParams}} + {{#pathParams}} + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString())); + {{#-last}} + + {{/-last}} + {{/pathParams}} + {{#queryParams}} + {{#-first}} + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + {{/-first}} + {{/queryParams}} + {{^queryParams}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInQuery}} + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + {{/queryParams}} + {{#queryParams}} + {{#required}} + {{#-first}} + + {{/-first}} + parseQueryStringLocalVar["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}}); + {{/required}} + {{/queryParams}} + + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + parseQueryStringLocalVar["{{baseName}}"] = ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}}); // Constant query parameter + {{/isQueryParam}} + {{/constantParams}} + {{#queryParams}} + {{^required}} + if ({{paramName}}.IsSet) + // here too + parseQueryStringLocalVar["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}}.Value); + + {{/required}} + {{#-last}} + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + {{/-last}} + {{/queryParams}} + {{#constantParams}} + {{#isHeaderParam}} + // Set client side default value of Header Param "{{baseName}}". + httpRequestMessageLocalVar.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant header parameter + {{/isHeaderParam}} + {{/constantParams}} + {{#headerParams}} + {{#required}} + httpRequestMessageLocalVar.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}})); + + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + httpRequestMessageLocalVar.Headers.Add("{{baseName}}", ClientUtils.ParameterToString({{paramName}}.Value)); + + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#-first}} + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars));{{/-first}}{{^isFile}}{{#required}} + + formParameterLocalVars.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}))); + + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + formParameterLocalVars.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}.Value))); + + {{/required}} + {{/isFile}} + {{#isFile}} + {{#required}} + multipartContentLocalVar.Add(new StreamContent({{paramName}})); + + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + multipartContentLocalVar.Add(new StreamContent({{paramName}}.Value)); + + {{/required}} + {{/isFile}} + {{/formParams}} + {{#bodyParam}} + {{#required}} + httpRequestMessageLocalVar.Content = ({{paramName}}{{^required}}.Value{{/required}} as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize({{paramName}}{{^required}}.Value{{/required}}, _jsonSerializerOptions)); + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + httpRequestMessageLocalVar.Content = ({{paramName}}{{^required}}.Value{{/required}} as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize({{paramName}}{{^required}}.Value{{/required}}, _jsonSerializerOptions)); + {{/required}} + + {{/bodyParam}} + {{#authMethods}} + {{#-first}} + List tokenBaseLocalVars = new List(); + {{/-first}} + {{#isApiKey}} + {{^isKeyInCookie}} + ApiKeyToken apiKeyTokenLocalVar{{-index}} = (ApiKeyToken) await ApiKeyProvider.GetAsync("{{keyParamName}}", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar{{-index}}); + {{#isKeyInHeader}} + apiKeyTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar); + + {{/isKeyInHeader}} + {{/isKeyInCookie}} + {{#isKeyInQuery}} + + apiKeyTokenLocalVar{{-index}}.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + {{#authMethods}} + {{#isBasicBasic}} + + BasicToken basicTokenLocalVar{{-index}} = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(basicTokenLocalVar{{-index}}); + + basicTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + {{/isBasicBasic}} + {{#isBasicBearer}} + + BearerToken bearerTokenLocalVar{{-index}} = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(bearerTokenLocalVar{{-index}}); + + bearerTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + {{/isBasicBearer}} + {{#isOAuth}} + + OAuthToken oauthTokenLocalVar{{-index}} = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar{{-index}}); + + oauthTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + {{/isOAuth}} + {{#isHttpSignature}} + + HttpSignatureToken httpSignatureTokenLocalVar{{-index}} = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar{{-index}}); + + if (httpRequestMessageLocalVar.Content != null) { + string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); + + httpSignatureTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + } + {{/isHttpSignature}} + {{/authMethods}} + {{#consumes}} + {{#-first}} + + {{=<% %>=}} + string[] contentTypes = new string[] {<%/-first%> + <%={{ }}=%> + "{{{mediaType}}}"{{^-last}},{{/-last}}{{#-last}} + }; + {{/-last}} + {{/consumes}} + {{#consumes}} + {{#-first}} + + string{{nrt?}} contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + {{/-first}} + {{/consumes}} + {{#produces}} + {{#-first}} + + {{=<% %>=}} + string[] acceptLocalVars = new string[] {<%/-first%> + <%={{ }}=%> + "{{{mediaType}}}"{{^-last}},{{/-last}}{{#-last}} + }; + {{/-last}} + {{/produces}} + {{#produces}} + {{#-first}} + + string{{nrt?}} acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + {{/-first}} + {{/produces}} + {{#net60OrLater}} + + httpRequestMessageLocalVar.Method = HttpMethod.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}; + {{/net60OrLater}} + {{^net60OrLater}} + httpRequestMessageLocalVar.Method = new HttpMethod("{{#lambda.uppercase}}{{httpMethod}}{{/lambda.uppercase}}"); + {{/net60OrLater}} + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); + + ILogger<{{operationId}}ApiResponse> apiResponseLoggerLocalVar = LoggerFactory.CreateLogger<{{operationId}}ApiResponse>(); + + {{operationId}}ApiResponse apiResponseLocalVar = new{{^net60OrLater}} {{operationId}}ApiResponse{{/net60OrLater}}(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "{{path}}", requestedAtLocalVar, _jsonSerializerOptions); + + After{{operationId}}DefaultImplementation({{#lambda.joinWithComma}}apiResponseLocalVar {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); + + Events.ExecuteOn{{operationId}}(apiResponseLocalVar); + + {{#authMethods}} + {{#-first}} + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + {{/-first}} + {{/authMethods}} + {{#net80OrLater}} + {{#responses}} + {{#vendorExtensions.x-set-cookie}} + if (httpResponseMessageLocalVar.StatusCode == (HttpStatusCode) {{code}} && httpResponseMessageLocalVar.Headers.TryGetValues("Set-Cookie", out var cookieHeadersLocalVar)) + { + foreach(string cookieHeader in cookieHeadersLocalVar) + { + IList setCookieHeaderValuesLocalVar = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeadersLocalVar.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValueLocalVar in setCookieHeaderValuesLocalVar) + { + Cookie cookieLocalVar = new Cookie(setCookieHeaderValueLocalVar.Name.ToString(), setCookieHeaderValueLocalVar.Value.ToString()) + { + HttpOnly = setCookieHeaderValueLocalVar.HttpOnly + }; + + if (setCookieHeaderValueLocalVar.Expires.HasValue) + cookieLocalVar.Expires = setCookieHeaderValueLocalVar.Expires.Value.UtcDateTime; + + if (setCookieHeaderValueLocalVar.Path.HasValue) + cookieLocalVar.Path = setCookieHeaderValueLocalVar.Path.Value; + + if (setCookieHeaderValueLocalVar.Domain.HasValue) + cookieLocalVar.Domain = setCookieHeaderValueLocalVar.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilderLocalVar.Scheme}://{uriBuilderLocalVar.Host}"), cookieLocalVar); + } + } + } + + {{/vendorExtensions.x-set-cookie}} + {{/responses}} + {{/net80OrLater}} + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnError{{operationId}}DefaultImplementation({{#lambda.joinWithComma}}e "{{path}}" uriBuilderLocalVar.Path {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); + Events.ExecuteOnError{{operationId}}(e); + throw; + } + {{/lambda.trimLineBreaks}} + } + {{#responses}} + {{#-first}} + + /// + /// The + /// + {{>visibility}} partial class {{operationId}}ApiResponse : {{packageName}}.{{clientPackage}}.ApiResponse, {{interfacePrefix}}{{operationId}}ApiResponse + { + /// + /// The logger + /// + public ILogger<{{operationId}}ApiResponse> Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public {{operationId}}ApiResponse(ILogger<{{operationId}}ApiResponse> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + {{#responses}} + + {{#vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is the default response type + /// + /// + public bool Is{{vendorExtensions.x-http-status}} => {{#vendorExtensions.x-only-default}}true{{/vendorExtensions.x-only-default}}{{^vendorExtensions.x-only-default}}{{#lambda.joinConditions}}{{#responses}}{{^vendorExtensions.x-http-status-is-default}}!Is{{vendorExtensions.x-http-status}} {{/vendorExtensions.x-http-status-is-default}}{{/responses}}{{/lambda.joinConditions}}{{/vendorExtensions.x-only-default}}; + {{/vendorExtensions.x-http-status-is-default}} + {{^vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}} + /// + /// + public bool Is{{vendorExtensions.x-http-status}} => {{code}} == (int)StatusCode; + {{/vendorExtensions.x-http-status-is-default}} + {{#dataType}} + + /// + /// Deserializes the response if the response is {{code}} {{vendorExtensions.x-http-status}} + /// + /// + public {{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{vendorExtensions.x-http-status}}() + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>AsModel}} + {{/lambda.indent4}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}} and the deserialized response is not null + /// + /// + /// + public bool Try{{vendorExtensions.x-http-status}}({{#net60OrLater}}[NotNullWhen(true)]{{/net60OrLater}}out {{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} result) + { + result = null; + + try + { + result = {{vendorExtensions.x-http-status}}(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode){{code}}); + } + + return result != null; + } + {{/dataType}} + {{#-last}} + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>OnDeserializationError}} + {{/lambda.indent4}} + {{/lambda.trimTrailingWithNewLine}} + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + {{/-last}} + {{/responses}} + } + {{/-first}} + {{/responses}} + {{/operation}} + } + {{/operations}} +} +{{/lambda.trimLineBreaks}} diff --git a/generation/templates/libraries/generichost/api_test.mustache b/generation/templates/libraries/generichost/api_test.mustache new file mode 100644 index 00000000..02ce2216 --- /dev/null +++ b/generation/templates/libraries/generichost/api_test.mustache @@ -0,0 +1,51 @@ +{{>partial_header}} +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{apiPackage}};{{#hasImport}} +using {{packageName}}.{{modelPackage}};{{/hasImport}} + + +{{>testInstructions}} + + +namespace {{packageName}}.Test.{{apiPackage}} +{ + /// + /// Class for testing {{classname}} + /// + public sealed class {{classname}}Tests : ApiTestsBase + { + private readonly {{interfacePrefix}}{{classname}} _instance; + + public {{classname}}Tests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}} + /// + [Fact (Skip = "not implemented")] + public async Task {{operationId}}AsyncTest() + { + {{#allParams}} + {{^required}}Client.Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} = default{{nrt!}}; + {{/allParams}} + {{#returnType}} + var response = await _instance.{{operationId}}Async({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + var model = response.{{#lambda.first}}{{#responses}}{{vendorExtensions.x-http-status}} {{/responses}}{{/lambda.first}}(); + Assert.IsType<{{{.}}}>(model); + {{/returnType}} + {{^returnType}} + await _instance.{{operationId}}Async({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/returnType}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/generation/templates/libraries/generichost/git_push.ps1.mustache b/generation/templates/libraries/generichost/git_push.ps1.mustache new file mode 100644 index 00000000..f263c2bc --- /dev/null +++ b/generation/templates/libraries/generichost/git_push.ps1.mustache @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "{{{gitHost}}}", + [Parameter()][Alias("u")][String]$GitUserId = "{{{gitUserId}}}", + [Parameter()][Alias("r")][String]$GitRepoId = "{{{gitRepoId}}}", + [Parameter()][Alias("m")][string]$Message = "{{{releaseNote}}}", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/generation/templates/libraries/generichost/git_push.sh.mustache b/generation/templates/libraries/generichost/git_push.sh.mustache new file mode 100644 index 00000000..3d4b710d --- /dev/null +++ b/generation/templates/libraries/generichost/git_push.sh.mustache @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-{{{gitUserId}}}} +git_repo_id=${2:-{{{gitRepoId}}}} +release_note=${3:-{{{releaseNote}}}} +git_host=${4:-{{{gitHost}}}} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/generation/templates/libraries/generichost/model.mustache b/generation/templates/libraries/generichost/model.mustache new file mode 100644 index 00000000..f9931574 --- /dev/null +++ b/generation/templates/libraries/generichost/model.mustache @@ -0,0 +1,50 @@ +// +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +{{^useGenericHost}} +using System.Runtime.Serialization; +{{/useGenericHost}} +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#useGenericHost}} +{{#useSourceGeneration}} +using System.Text.Json.Serialization.Metadata; +{{/useSourceGeneration}} +using {{packageName}}.{{clientPackage}}; +{{/useGenericHost}} +{{#models}} +{{#lambda.trimTrailingWithNewLine}} +{{#model}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}} +{{>modelEnum}} +{{/isEnum}} +{{^isEnum}} +{{>modelGeneric}} + +{{>JsonConverter}} +{{/isEnum}} +{{>SourceGenerationContext}} +{{/model}} +{{/lambda.trimTrailingWithNewLine}} +{{/models}} +} diff --git a/generation/templates/libraries/generichost/modelGeneric.mustache b/generation/templates/libraries/generichost/modelGeneric.mustache new file mode 100644 index 00000000..ad821487 --- /dev/null +++ b/generation/templates/libraries/generichost/modelGeneric.mustache @@ -0,0 +1,377 @@ + /// + /// {{description}}{{^description}}{{classname}}{{/description}} + /// + {{>visibility}} partial class {{classname}}{{#lambda.firstDot}}{{#parent}} : .{{/parent}}{{#validatable}} : .{{/validatable}}{{#equatable}}{{#readOnlyVars}}{{#-first}} : .{{/-first}}{{/readOnlyVars}}{{/equatable}}{{/lambda.firstDot}}{{#lambda.joinWithComma}}{{#parent}}{{{.}}} {{/parent}}{{>ImplementsIEquatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + { + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + /// + /// Initializes a new instance of the class. + /// + /// + {{#composedSchemas.anyOf}} + /// + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + /// {{description}}{{^description}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + {{/isDiscriminator}} + {{/allVars}} + {{#model.vendorExtensions.x-model-is-mutable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutable}}{{^model.vendorExtensions.x-model-is-mutable}}internal{{/model.vendorExtensions.x-model-is-mutable}} {{classname}}({{#lambda.joinWithComma}}{{{dataType}}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{#model.composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{baseType}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{/model.composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{parent}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + { + {{#composedSchemas.anyOf}} + {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/composedSchemas.anyOf}} + {{name}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{#allVars}} + {{^isDiscriminator}} + {{^isInherited}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isInherited}} + {{#isInherited}} + {{#isNew}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isNew}} + {{/isInherited}} + {{/isDiscriminator}} + {{/allVars}} + OnCreated(); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{^composedSchemas.oneOf}} + /// + /// Initializes a new instance of the class. + /// + {{#composedSchemas.anyOf}} + /// + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + /// {{description}}{{^description}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + {{/isDiscriminator}} + {{/allVars}} + {{^composedSchemas.anyOf}} + [JsonConstructor] + {{/composedSchemas.anyOf}} + {{#model.vendorExtensions.x-model-is-mutable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutable}}{{^model.vendorExtensions.x-model-is-mutable}}internal{{/model.vendorExtensions.x-model-is-mutable}} {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{baseType}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{/composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + { + {{#composedSchemas.anyOf}} + {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + {{^isInherited}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isInherited}} + {{#isInherited}} + {{#isNew}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isNew}} + {{/isInherited}} + {{/isDiscriminator}} + {{/allVars}} + OnCreated(); + } + + {{/composedSchemas.oneOf}} + partial void OnCreated(); + + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/isEnum}} + {{^isDiscriminator}} + {{#isEnum}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#example}} + /// {{.}} + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{#isNew}}new {{/isNew}}{{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{name}}Option; } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isEnum}} + {{/isDiscriminator}} + {{/vars}} + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{description}}{{^description}}Gets or Sets {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /// {{.}} + {{/example}} + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option; } {{^isReadOnly}}set { this.{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + /// + /// {{description}}{{^description}}Gets or Sets {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /// {{.}} + {{/example}} + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{dataType}}}{{>NullConditionalProperty}} {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{#allVars}} + {{#isDiscriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + /// + /// The discriminator + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}{{datatypeWithEnum}} {{name}} { get; } = {{^isNew}}"{{classname}}"{{/isNew}}{{#isNew}}{{^isEnum}}"{{classname}}"{{/isEnum}}{{#isEnum}}({{datatypeWithEnum}})Enum.Parse(typeof({{datatypeWithEnum}}), "{{classname}}"){{/isEnum}}{{/isNew}}; + + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/isDiscriminator}} + {{^isDiscriminator}} + {{^isEnum}} + {{#isInherited}} + {{#isNew}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public new Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /// {{.}} + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public new {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{name}}Option } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isNew}} + {{/isInherited}} + {{^isInherited}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /// {{.}} + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{name}}Option; } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isInherited}} + {{/isEnum}} + {{/isDiscriminator}} + {{/allVars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#parent}} + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + {{/parent}} + {{#vars}} + {{^isDiscriminator}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/isDiscriminator}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + sb.Append("}\n"); + return sb.ToString(); + } + {{#equatable}} + {{#readOnlyVars}} + {{#-first}} + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object{{nrt?}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}}{{nrt?}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return {{#parent}}base.Equals(input) && {{/parent}}{{#readOnlyVars}}{{^isInherited}}{{^isContainer}} + ( + {{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}} + ({{name}} != null && + {{name}}.Equals(input.{{name}})) + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + {{name}}.Equals(input.{{name}}) + {{/vendorExtensions.x-is-value-type}} + ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} + ( + {{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}{{name}} != null && + input.{{name}} != null && + {{/vendorExtensions.x-is-value-type}}{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + && (AdditionalProperties.Count == input.AdditionalProperties.Count && !AdditionalProperties.Except(input.AdditionalProperties).Any()); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + {{#parent}} + int hashCode = base.GetHashCode(); + {{/parent}} + {{^parent}} + int hashCode = 41; + {{/parent}} + {{#readOnlyVars}} + {{#required}} + {{^isNullable}} + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/isNullable}} + {{/required}} + {{/readOnlyVars}} + {{#readOnlyVars}} + {{#lambda.copy}} + + if ({{name}} != null) + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/lambda.copy}} + {{#isNullable}} + {{#lambda.pasteOnce}}{{/lambda.pasteOnce}} + {{/isNullable}} + {{^required}} + {{#lambda.pasteOnce}}{{/lambda.pasteOnce}} + {{/required}} + {{/readOnlyVars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + + return hashCode; + } + } + {{/-first}} + {{/readOnlyVars}} + {{/equatable}} +{{#validatable}} +{{^parentModel}} + +{{>validatable}} +{{/parentModel}} +{{/validatable}} + } \ No newline at end of file diff --git a/generation/templates/libraries/generichost/testInstructions.mustache b/generation/templates/libraries/generichost/testInstructions.mustache new file mode 100644 index 00000000..7bf738e2 --- /dev/null +++ b/generation/templates/libraries/generichost/testInstructions.mustache @@ -0,0 +1,18 @@ +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ \ No newline at end of file diff --git a/generation/templates/libraries/httpclient/ApiClient.mustache b/generation/templates/libraries/httpclient/ApiClient.mustache new file mode 100644 index 00000000..9bed800e --- /dev/null +++ b/generation/templates/libraries/httpclient/ApiClient.mustache @@ -0,0 +1,792 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^netStandard}} +using System.Web; +{{/netStandard}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using System.Net.Http; +using System.Net.Http.Headers; +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} + +namespace {{packageName}}.Client +{ + /// + /// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public async Task Deserialize(HttpResponseMessage response) + { + var result = (T) await Deserialize(response, typeof(T)).ConfigureAwait(false); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal async Task Deserialize(HttpResponseMessage response, Type type) + { + IList headers = new List(); + // process response headers, e.g. Access-Control-Allow-Methods + foreach (var responseHeader in response.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // process response content headers, e.g. Content-Type + foreach (var responseHeader in response.Content.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // RFC 2183 & RFC 2616 + var fileNameRegex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$", RegexOptions.IgnoreCase); + if (type == typeof(byte[])) // return byte array + { + return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + } + else if (type == typeof(FileParameter)) + { + if (headers != null) { + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + return new FileParameter(fileName, await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + } + } + return new FileParameter(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + if (headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false), null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + /// + /// The Dispose method will manage the HttpClient lifecycle when not passed by constructor. + /// + {{>visibility}} partial class ApiClient : IDisposable, ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + public ApiClient() : + this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) + { + } + + /// + /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); + _disposeClient = true; + _baseUrl = basePath; + } + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath, handler) + { + } + + /// + /// Initializes a new instance of the . + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + if(_disposeClient) { + _httpClient.Dispose(); + } + } + + /// Prepares multipart/form-data content + {{! TODO: Add handling of improper usage }} + HttpContent PrepareMultipartFormDataContent(RequestOptions options) + { + string boundary = "---------" + Guid.NewGuid().ToString().ToUpperInvariant(); + var multipartContent = new MultipartFormDataContent(boundary); + foreach (var formParameter in options.FormParameters) + { + multipartContent.Add(new StringContent(formParameter.Value), formParameter.Key); + } + + if (options.FileParameters != null && options.FileParameters.Count > 0) + { + foreach (var fileParam in options.FileParameters) + { + foreach (var file in fileParam.Value) + { + var content = new StreamContent(file.Content); + content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType); + multipartContent.Add(content, fileParam.Key, file.Name); + } + } + } + return multipartContent; + } + + /// + /// Provides all logic for constructing a new HttpRequestMessage. + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the a HttpRequestMessage. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new HttpRequestMessage instance. + /// + private HttpRequestMessage NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path); + + builder.AddPathParameters(options.PathParameters); + + builder.AddQueryParameters(options.QueryParameters); + + HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); + + if (configuration.UserAgent != null) + { + request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent); + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.Headers.Add(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + // Todo make content headers actually content headers + request.Headers.TryAddWithoutValidation(headerParam.Key, value); + } + } + } + + List> contentList = new List>(); + + string contentType = null; + if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type")) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes.FirstOrDefault(); + } + + {{!// TODO Add error handling in case of improper usage}} + if (contentType == "multipart/form-data") + { + request.Content = PrepareMultipartFormDataContent(options); + } + else if (contentType == "application/x-www-form-urlencoded") + { + request.Content = new FormUrlEncodedContent(options.FormParameters); + } + else + { + if (options.Data != null) + { + if (options.Data is FileParameter fp) + { + contentType = contentType ?? "application/octet-stream"; + + var streamContent = new StreamContent(fp.Content); + streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + request.Content = streamContent; + } + else + { + var serializer = new CustomJsonCodec(SerializerSettings, configuration); + request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(), + "application/json"); + } + } + } + + + + // TODO provide an alternative that allows cookies per request instead of per API client + if (options.Cookies != null && options.Cookies.Count > 0) + { + request.Properties["CookieContainer"] = options.Cookies; + } + + return request; + } + + partial void InterceptRequest(HttpRequestMessage req); + partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); + + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + { + T result = (T) responseData; + string rawContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ReasonPhrase, + Cookies = new List() + }; + + // process response headers, e.g. Access-Control-Allow-Methods + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + // process response content headers, e.g. Content-Type + if (response.Content.Headers != null) + { + foreach (var responseHeader in response.Content.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (_httpClientHandler != null && response != null) + { + try { + foreach (Cookie cookie in _httpClientHandler.CookieContainer.GetCookies(uri)) + { + transformed.Cookies.Add(cookie); + } + } + catch (PlatformNotSupportedException) {} + } + + return transformed; + } + + private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) + { + return ExecAsync(req, configuration).GetAwaiter().GetResult(); + } + + private async Task> ExecAsync(HttpRequestMessage req, + IReadableConfiguration configuration, + System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + CancellationTokenSource timeoutTokenSource = null; + CancellationTokenSource finalTokenSource = null; + var deserializer = new CustomJsonCodec(SerializerSettings, configuration); + var finalToken = cancellationToken; + + try + { + if (configuration.Timeout > 0) + { + timeoutTokenSource = new CancellationTokenSource(configuration.Timeout); + finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token); + finalToken = finalTokenSource.Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { + {{/supportsRetry}} + response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri).ConfigureAwait(false); + } + + object responseData = await deserializer.Deserialize(response).ConfigureAwait(false); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri).ConfigureAwait(false); + } + catch (OperationCanceledException original) + { + if (timeoutTokenSource != null && timeoutTokenSource.IsCancellationRequested) + { + throw new TaskCanceledException($"[{req.Method}] {req.RequestUri} was timeout.", + new TimeoutException(original.Message, original)); + } + throw; + } + finally + { + if (timeoutTokenSource != null) + { + timeoutTokenSource.Dispose(); + } + + if (finalTokenSource != null) + { + finalTokenSource.Dispose(); + } + } + } + + {{#supportsAsync}} + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(new HttpMethod("PATCH"), path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(new HttpMethod("PATCH"), path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/generation/templates/libraries/httpclient/FileParameter.mustache b/generation/templates/libraries/httpclient/FileParameter.mustache new file mode 100644 index 00000000..87e5fcdc --- /dev/null +++ b/generation/templates/libraries/httpclient/FileParameter.mustache @@ -0,0 +1,72 @@ +{{>partial_header}} + +using System.IO; + +namespace {{packageName}}.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content type of the file + /// + public string ContentType { get; set; } = "application/octet-stream"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The content type of the file + /// The file content + public FileParameter(string filename, string contentType, Stream content) + { + Name = filename; + ContentType = contentType; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/generation/templates/libraries/httpclient/RequestOptions.mustache b/generation/templates/libraries/httpclient/RequestOptions.mustache new file mode 100644 index 00000000..25e76d03 --- /dev/null +++ b/generation/templates/libraries/httpclient/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Multimap FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Multimap(); + Cookies = new List(); + } + } +} diff --git a/generation/templates/libraries/httpclient/api.mustache b/generation/templates/libraries/httpclient/api.mustache new file mode 100644 index 00000000..22c8fd0c --- /dev/null +++ b/generation/templates/libraries/httpclient/api.mustache @@ -0,0 +1,766 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{.}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : IDisposable, {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// The target service's base path in URL format. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// An instance of Configuration. + /// + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// + /// An instance of HttpClient. + /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, {{packageName}}.Client.Configuration configuration, HttpClientHandler handler = null) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + /// + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + this.ApiClient?.Dispose(); + } + + /// + /// Holds the ApiClient if created + /// + public {{packageName}}.Client.ApiClient ApiClient { get; set; } = null; + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#constantParams}} + {{#isPathParam}} + // Set client side default value of Path Param "{{baseName}}". + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant path parameter + {{/isPathParam}} + {{/constantParams}} + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + localVarRequestOptions.QueryParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant query parameter + {{/isQueryParam}} + {{/constantParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#constantParams}} + {{#isHeaderParam}} + // Set client side default value of Header Param "{{baseName}}". + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}})); // Constant header parameter + {{/isHeaderParam}} + {{/constantParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/generation/templates/libraries/httpclient/model.mustache b/generation/templates/libraries/httpclient/model.mustache new file mode 100644 index 00000000..f84de7f6 --- /dev/null +++ b/generation/templates/libraries/httpclient/model.mustache @@ -0,0 +1,51 @@ +{{>partial_header}} + +{{#models}} +{{#model}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +{{#vendorExtensions.x-com-visible}} +using System.Runtime.InteropServices; +{{/vendorExtensions.x-com-visible}} +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using FileParameter = {{packageName}}.Client.FileParameter; +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#anyOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/anyOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/generation/templates/libraries/unityWebRequest/ApiClient.mustache b/generation/templates/libraries/unityWebRequest/ApiClient.mustache new file mode 100644 index 00000000..908c829f --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/ApiClient.mustache @@ -0,0 +1,639 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using System.Net.Http; +using System.Net.Http.Headers; +using UnityEngine.Networking; +using UnityEngine; + +namespace {{packageName}}.Client +{ + /// + /// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public T Deserialize(UnityWebRequest request) + { + var result = (T) Deserialize(request, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The UnityWebRequest after it has a response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(UnityWebRequest request, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return request.downloadHandler.data; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + // NOTE: Ignoring Content-Disposition filename support, since not all platforms + // have a location on disk to write arbitrary data (tvOS, consoles). + return new MemoryStream(request.downloadHandler.data); + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(request.downloadHandler.text, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(request.downloadHandler.text, type); + } + + var contentType = request.GetResponseHeader("Content-Type"); + + if (!string.IsNullOrEmpty(contentType) && contentType.Contains("application/json")) + { + var text = request.downloadHandler?.text; + + // Generated APIs that don't expect a return value provide System.Object as the type + if (type == typeof(System.Object) && (string.IsNullOrEmpty(text) || text.Trim() == "null")) + { + return null; + } + + if (request.responseCode >= 200 && request.responseCode < 300) + { + try + { + // Deserialize as a model + return JsonConvert.DeserializeObject(text, type, _serializerSettings); + } + catch (Exception e) + { + throw new UnexpectedResponseException(request, type, e.ToString()); + } + } + else + { + throw new ApiException((int)request.responseCode, request.error, text); + } + } + + if (type != typeof(System.Object) && request.responseCode >= 200 && request.responseCode < 300) + { + throw new UnexpectedResponseException(request, type); + } + + return null; + + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + /// + /// The Dispose method will manage the HttpClient lifecycle when not passed by constructor. + /// + {{>visibility}} partial class ApiClient : IDisposable, ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() : + this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) + { + } + + /// + /// Initializes a new instance of the . + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + } + + /// + /// Provides all logic for constructing a new UnityWebRequest. + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the UnityWebRequest. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new UnityWebRequest instance. + /// + private UnityWebRequest NewRequest( + string method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path); + + builder.AddPathParameters(options.PathParameters); + + builder.AddQueryParameters(options.QueryParameters); + + string contentType = null; + if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type")) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes.FirstOrDefault(); + } + + var uri = builder.GetFullUri(); + UnityWebRequest request = null; + + if (contentType == "multipart/form-data") + { + var formData = new List(); + foreach (var formParameter in options.FormParameters) + { + formData.Add(new MultipartFormDataSection(formParameter.Key, formParameter.Value)); + } + + request = UnityWebRequest.Post(uri, formData); + request.method = method; + } + else if (contentType == "application/x-www-form-urlencoded") + { + var form = new WWWForm(); + foreach (var kvp in options.FormParameters) + { + form.AddField(kvp.Key, kvp.Value); + } + + request = UnityWebRequest.Post(uri, form); + request.method = method; + } + else if (options.Data != null) + { + var serializer = new CustomJsonCodec(SerializerSettings, configuration); + var jsonData = serializer.Serialize(options.Data); + + // Making a post body application/json encoded is whack with UnityWebRequest. + // See: https://stackoverflow.com/questions/68156230/unitywebrequest-post-not-sending-body + request = UnityWebRequest.Put(uri, jsonData); + request.method = method; + request.SetRequestHeader("Content-Type", "application/json"); + } + else + { + request = new UnityWebRequest(builder.GetFullUri(), method); + } + + if (request.downloadHandler == null && typeof(T) != typeof(System.Object)) + { + request.downloadHandler = new DownloadHandlerBuffer(); + } + +#if UNITY_EDITOR || !UNITY_WEBGL + if (configuration.UserAgent != null) + { + request.SetRequestHeader("User-Agent", configuration.UserAgent); + } +#endif + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.SetRequestHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + // Todo make content headers actually content headers + request.SetRequestHeader(headerParam.Key, value); + } + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + #if UNITY_WEBGL + throw new System.InvalidOperationException("UnityWebRequest does not support setting cookies in WebGL"); + #else + if (options.Cookies.Count != 1) + { + UnityEngine.Debug.LogError("Only one cookie supported, ignoring others"); + } + + request.SetRequestHeader("Cookie", options.Cookies[0].ToString()); + #endif + } + + return request; + + } + + partial void InterceptRequest(UnityWebRequest req, string path, RequestOptions options, IReadableConfiguration configuration); + partial void InterceptResponse(UnityWebRequest req, string path, RequestOptions options, IReadableConfiguration configuration, ref object responseData); + + private ApiResponse ToApiResponse(UnityWebRequest request, object responseData) + { + T result = (T) responseData; + + var transformed = new ApiResponse((HttpStatusCode)request.responseCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, request.downloadHandler?.text ?? "") + { + ErrorText = request.error, + Cookies = new List() + }; + + // process response headers, e.g. Access-Control-Allow-Methods + var responseHeaders = request.GetResponseHeaders(); + if (responseHeaders != null) + { + foreach (var responseHeader in request.GetResponseHeaders()) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + return transformed; + } + + private async Task> ExecAsync( + UnityWebRequest request, + string path, + RequestOptions options, + IReadableConfiguration configuration, + System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var deserializer = new CustomJsonCodec(SerializerSettings, configuration); + + using (request) + { + if (configuration.Timeout > 0) + { + request.timeout = (int)Math.Ceiling(configuration.Timeout / 1000.0f); + } + + if (configuration.Proxy != null) + { + throw new InvalidOperationException("Configuration `Proxy` not supported by UnityWebRequest"); + } + + if (configuration.ClientCertificates != null) + { + // Only Android/iOS/tvOS/Standalone players can support certificates, and this + // implementation is intended to work on all platforms. + // + // TODO: Could optionally allow support for this on these platforms. + // + // See: https://docs.unity3d.com/ScriptReference/Networking.CertificateHandler.html + throw new InvalidOperationException("Configuration `ClientCertificates` not supported by UnityWebRequest on all platforms"); + } + + InterceptRequest(request, path, options, configuration); + + var asyncOp = request.SendWebRequest(); + + TaskCompletionSource tsc = new TaskCompletionSource(); + asyncOp.completed += (_) => tsc.TrySetResult(request.result); + + using (var tokenRegistration = cancellationToken.Register(request.Abort, true)) + { + await tsc.Task; + } + + if (request.result == UnityWebRequest.Result.ConnectionError || + request.result == UnityWebRequest.Result.DataProcessingError) + { + throw new ConnectionException(request); + } + + object responseData = deserializer.Deserialize(request); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { new ByteArrayContent(request.downloadHandler.data) }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) new MemoryStream(request.downloadHandler.data); + } + + InterceptResponse(request, path, options, configuration, ref responseData); + + return ToApiResponse(request, responseData); + } + } + + {{#supportsAsync}} + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("GET", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("POST", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("PUT", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("DELETE", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("HEAD", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("OPTIONS", path, options, config), path, options, config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest("PATCH", path, options, config), path, options, config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + throw new System.NotImplementedException("UnityWebRequest does not support synchronous operation"); + } + #endregion ISynchronousClient + } +} \ No newline at end of file diff --git a/generation/templates/libraries/unityWebRequest/ConnectionException.mustache b/generation/templates/libraries/unityWebRequest/ConnectionException.mustache new file mode 100644 index 00000000..108ea3bf --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/ConnectionException.mustache @@ -0,0 +1,21 @@ +{{>partial_header}} + +using System; +using UnityEngine.Networking; + +namespace {{packageName}}.Client +{ + public class ConnectionException : Exception + { + public UnityWebRequest.Result Result { get; private set; } + public string Error { get; private set; } + + // NOTE: Cannot keep reference to the request since it will be disposed. + public ConnectionException(UnityWebRequest request) + : base($"result={request.result} error={request.error}") + { + Result = request.result; + Error = request.error ?? ""; + } + } +} diff --git a/generation/templates/libraries/unityWebRequest/README.mustache b/generation/templates/libraries/unityWebRequest/README.mustache new file mode 100644 index 00000000..b0a140dd --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/README.mustache @@ -0,0 +1,175 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Version support +This generator should support all current LTS versions of Unity +- Unity 2020.3 (LTS) and up +- .NET Standard 2.1 / .NET Framework + + +## Dependencies + +- [Newtonsoft.Json](https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html) - 3.0.2 or later +- [Unity Test Framework](https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/index.html) - 1.1.33 or later + + +## Installation +Add the dependencies to `Packages/manifest.json` +``` +{ + "dependencies": { + ... + "com.unity.nuget.newtonsoft-json": "3.0.2", + "com.unity.test-framework": "1.1.33", + } +} +``` + +Then use the namespaces: +```csharp +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; +``` + + +## Getting Started + +```csharp +using System; +using System.Collections.Generic; +using UnityEngine; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace {{packageName}}Example +{ +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} + public class {{operationId}}Example : MonoBehaviour + { + async void Start() + { + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + var apiInstance = new {{classname}}(config); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}await apiInstance.{{{operationId}}}Async({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.Log(result);{{/returnType}} + Debug.Log("Done!"); + } + catch (ApiException e) + { + Debug.LogError("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.LogError("Status Code: "+ e.ErrorCode); + Debug.LogError(e.StackTrace); + } +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{{summary}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: Bearer Authentication +{{/isBasicBearer}} +{{#isHttpSignature}}- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/generation/templates/libraries/unityWebRequest/RequestOptions.mustache b/generation/templates/libraries/unityWebRequest/RequestOptions.mustache new file mode 100644 index 00000000..0dd18c4e --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/RequestOptions.mustache @@ -0,0 +1,60 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/generation/templates/libraries/unityWebRequest/UnexpectedResponseException.mustache b/generation/templates/libraries/unityWebRequest/UnexpectedResponseException.mustache new file mode 100644 index 00000000..a976b2a7 --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/UnexpectedResponseException.mustache @@ -0,0 +1,26 @@ +{{>partial_header}} + +using System; +using UnityEngine.Networking; + +namespace {{packageName}}.Client +{ + // Thrown when a backend doesn't return an expected response based on the expected type + // of the response data. + public class UnexpectedResponseException : Exception + { + public int ErrorCode { get; private set; } + + // NOTE: Cannot keep reference to the request since it will be disposed. + public UnexpectedResponseException(UnityWebRequest request, System.Type type, string extra = "") + : base(CreateMessage(request, type, extra)) + { + ErrorCode = (int)request.responseCode; + } + + private static string CreateMessage(UnityWebRequest request, System.Type type, string extra) + { + return $"httpcode={request.responseCode}, expected {type.Name} but got data: {extra}"; + } + } +} diff --git a/generation/templates/libraries/unityWebRequest/api.mustache b/generation/templates/libraries/unityWebRequest/api.mustache new file mode 100644 index 00000000..6b0a5883 --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/api.mustache @@ -0,0 +1,690 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{.}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : IDisposable, {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// The target service's base path in URL format. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHandler. + /// + /// An instance of Configuration. + /// + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + /// + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + this.ApiClient?.Dispose(); + } + + /// + /// Holds the ApiClient if created + /// + public {{packageName}}.Client.ApiClient ApiClient { get; set; } = null; + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// {{returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{{returnType}}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}}/// ApiResponse of {{returnType}}{{^returnType}}Object(void){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public {{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{returnType}}{{^returnType}}void{{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{.}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var task = {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken); + {{#returnType}} +#if UNITY_EDITOR || !UNITY_WEBGL + {{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await task.ConfigureAwait(false); +#else + {{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await task; +#endif + return localVarResponse.Data; + {{/returnType}} + {{^returnType}} +#if UNITY_EDITOR || !UNITY_WEBGL + await task.ConfigureAwait(false); +#else + await task; +#endif + {{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{.}}){{/returnType}} + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{{returnType}}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var task = this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken); + +#if UNITY_EDITOR || !UNITY_WEBGL + var localVarResponse = await task.ConfigureAwait(false); +#else + var localVarResponse = await task; +#endif + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/generation/templates/libraries/unityWebRequest/api_test.mustache b/generation/templates/libraries/unityWebRequest/api_test.mustache new file mode 100644 index 00000000..0f7f49f7 --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/api_test.mustache @@ -0,0 +1,74 @@ +{{>partial_header}} +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using NUnit.Framework; + +using {{packageName}}.Client; +using {{packageName}}.{{apiPackage}}; +{{#hasImport}} +// uncomment below to import models +//using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.Test.Api +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class {{classname}}Tests : IDisposable + { + {{^nonPublicApi}} + private {{classname}} instance; + + {{/nonPublicApi}} + public {{classname}}Tests() + { + {{^nonPublicApi}} + instance = new {{classname}}(); + {{/nonPublicApi}} + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Test] + public void {{operationId}}InstanceTest() + { + // TODO uncomment below to test 'IsType' {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}} + /// + [Test] + public void {{operationId}}Test() + { + // TODO uncomment below to test the method and replace null with proper value + {{#allParams}} + //{{{dataType}}} {{paramName}} = null; + {{/allParams}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}} + //Assert.IsType<{{{.}}}>(response); + {{/returnType}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/generation/templates/libraries/unityWebRequest/asmdef.mustache b/generation/templates/libraries/unityWebRequest/asmdef.mustache new file mode 100644 index 00000000..a30cba8c --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/asmdef.mustache @@ -0,0 +1,7 @@ +{ + "name": "{{packageName}}", + "overrideReferences": true, + "precompiledReferences": [ + "Newtonsoft.Json.dll" + ] +} diff --git a/generation/templates/libraries/unityWebRequest/asmdef_test.mustache b/generation/templates/libraries/unityWebRequest/asmdef_test.mustache new file mode 100644 index 00000000..c5e2d585 --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/asmdef_test.mustache @@ -0,0 +1,15 @@ +{ + "name": "{{testPackageName}}", + "references": [ + "{{packageName}}", + "UnityEngine.TestRunner" + ], + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll", + "Newtonsoft.Json.dll" + ], + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ] +} diff --git a/generation/templates/libraries/unityWebRequest/model.mustache b/generation/templates/libraries/unityWebRequest/model.mustache new file mode 100644 index 00000000..3c1c6c0e --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/model.mustache @@ -0,0 +1,47 @@ +{{>partial_header}} + +{{#models}} +{{#model}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +{{#vendorExtensions.x-com-visible}} +using System.Runtime.InteropServices; +{{/vendorExtensions.x-com-visible}} +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#anyOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/anyOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/generation/templates/libraries/unityWebRequest/model_test.mustache b/generation/templates/libraries/unityWebRequest/model_test.mustache new file mode 100644 index 00000000..40462328 --- /dev/null +++ b/generation/templates/libraries/unityWebRequest/model_test.mustache @@ -0,0 +1,64 @@ +{{>partial_header}} + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.{{clientPackage}}; +using System.Reflection; +using Newtonsoft.Json; +using NUnit.Framework; + +{{#models}} +{{#model}} +namespace {{packageName}}.Test.Model +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class {{classname}}Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; + + public {{classname}}Tests() + { + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Test] + public void {{classname}}InstanceTest() + { + // TODO uncomment below to test "IsType" {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + + {{#vars}} + /// + /// Test the property '{{name}}' + /// + [Test] + public void {{name}}Test() + { + // TODO unit test for the property '{{name}}' + } + {{/vars}} + } +} +{{/model}} +{{/models}} diff --git a/generation/templates/model.mustache b/generation/templates/model.mustache new file mode 100644 index 00000000..0d0c0b68 --- /dev/null +++ b/generation/templates/model.mustache @@ -0,0 +1,50 @@ +{{>partial_header}} + +{{#models}} +{{#model}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +{{#vendorExtensions.x-com-visible}} +using System.Runtime.InteropServices; +{{/vendorExtensions.x-com-visible}} +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#anyOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/anyOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/generation/templates/modelAnyOf.mustache b/generation/templates/modelAnyOf.mustache new file mode 100644 index 00000000..f3eac973 --- /dev/null +++ b/generation/templates/modelAnyOf.mustache @@ -0,0 +1,275 @@ +{{#model}} + /// + /// {{description}}{{^description}}{{classname}}{{/description}} + /// + {{#vendorExtensions.x-cls-compliant}} + [CLSCompliant({{{.}}})] + {{/vendorExtensions.x-cls-compliant}} + {{#vendorExtensions.x-com-visible}} + [ComVisible({{{.}}})] + {{/vendorExtensions.x-com-visible}} + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#lambda.joinWithComma}}{{#parent}}{{{.}}} {{/parent}}{{#equatable}}IEquatable<{{classname}}> {{/equatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + IsNullable = true; + SchemaType= "anyOf"; + } + + {{/isNullable}} + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^isNull}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{dataType}}. + public {{classname}}({{{dataType}}} actualInstance) + { + IsNullable = {{#model.isNullable}}true{{/model.isNullable}}{{^model.isNullable}}false{{/model.isNullable}}; + SchemaType= "anyOf"; + ActualInstance = actualInstance{{^model.isNullable}}{{^isPrimitiveType}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isPrimitiveType}}{{#isPrimitiveType}}{{#isArray}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isArray}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isFreeFormObject}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isString}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isString}}{{/isPrimitiveType}}{{/model.isNullable}}; + } + + {{/isNull}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#anyOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) + { + _actualInstance = value; + } + {{/anyOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#anyOf}} {{{.}}}{{^-last}},{{/-last}}{{/anyOf}}"); + } + } + } + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^isNull}} + + /// + /// Get the actual instance of `{{dataType}}`. If the actual instance is not `{{dataType}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{dataType}} + public {{{dataType}}} Get{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{#isArray}}{{#lambda.titlecase}}{{{dataFormat}}}{{/lambda.titlecase}}{{/isArray}}() + { + return ({{{dataType}}})ActualInstance; + } + {{/isNull}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return new{{classname}}; + } + {{#anyOf}} + + try + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/anyOf}} + + // no match found, throw an exception + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + {{#equatable}} + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (ActualInstance != null) + hashCode = hashCode * 59 + ActualInstance.GetHashCode(); + return hashCode; + } + } + {{/equatable}} + + {{#validatable}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + {{/validatable}} + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + switch(reader.TokenType) + { + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{#isInteger}} + case JsonToken.Integer: + return new {{classname}}(Convert.ToInt32(reader.Value)); + {{/isInteger}} + {{#isNumber}} + case JsonToken.Float: + return new {{classname}}(Convert.ToDecimal(reader.Value)); + {{/isNumber}} + {{#isString}} + case JsonToken.String: + return new {{classname}}(Convert.ToString(reader.Value)); + {{/isString}} + {{#isBoolean}} + case JsonToken.Boolean: + return new {{classname}}(Convert.ToBoolean(reader.Value)); + {{/isBoolean}} + {{#isDate}} + case JsonToken.Date: + return new {{classname}}(Convert.ToDateTime(reader.Value)); + {{/isDate}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + case JsonToken.StartObject: + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + case JsonToken.StartArray: + return {{classname}}.FromJson(JArray.Load(reader).ToString(Formatting.None)); + default: + return null; + } + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } +{{/model}} \ No newline at end of file diff --git a/generation/templates/modelEnum.mustache b/generation/templates/modelEnum.mustache new file mode 100644 index 00000000..37fb53f5 --- /dev/null +++ b/generation/templates/modelEnum.mustache @@ -0,0 +1,185 @@ + /// + /// {{description}}{{^description}}Defines {{{name}}}{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#vendorExtensions.x-cls-compliant}} + [CLSCompliant({{{.}}})] + {{/vendorExtensions.x-cls-compliant}} + {{#vendorExtensions.x-com-visible}} + [ComVisible({{{.}}})] + {{/vendorExtensions.x-com-visible}} + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + {{^useGenericHost}} + [JsonConverter(typeof(StringEnumConverter))] + {{/useGenericHost}} + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{>visibility}} enum {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{value}} + /// + {{#isString}} + {{^useGenericHost}} + {{! EnumMember not currently supported in System.Text.Json, use a converter instead }} + [EnumMember(Value = "{{{value}}}")] + {{/useGenericHost}} + {{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}}{{^vendorExtensions.x-zero-based-enum}} = {{-index}}{{/vendorExtensions.x-zero-based-enum}}{{/isString}}{{^-last}},{{/-last}} + {{^-last}} + + {{/-last}} + {{/enumVars}} + {{/allowableValues}} + } + {{#useGenericHost}} + + /// + /// Converts to and from the JSON value + /// + public static class {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} FromString(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value.Equals({{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}})) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Could not convert value to type {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? FromStringOrDefault(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value.Equals({{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}})) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static {{>EnumValueDataType}} ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} value) + { + {{^isString}} + return ({{>EnumValueDataType}}) value; + {{/isString}} + {{#isString}} + {{#allowableValues}} + {{#enumVars}} + if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}) + return {{^isNumeric}}"{{/isNumeric}}{{{value}}}{{^isNumeric}}"{{/isNumeric}}; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Value could not be handled: '{value}'"); + {{/isString}} + } + } + + /// + /// A Json converter for type + /// + /// + public class {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}JsonConverter : JsonConverter<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> + { + /// + /// Returns a {{datatypeWithEnum}} from the Json object + /// + /// + /// + /// + /// + public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string{{nrt?}} rawValue = reader.GetString(); + + {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = rawValue == null + ? null + : {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions options) + { + writer.WriteStringValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableJsonConverter : JsonConverter<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}?> + { + /// + /// Returns a {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} from the Json object + /// + /// + /// + /// + /// + public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string{{nrt?}} rawValue = reader.GetString(); + + {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = rawValue == null + ? null + : {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? {{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions options) + { + writer.WriteStringValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}?.ToString() ?? "null"); + } + } + {{/useGenericHost}} diff --git a/generation/templates/modelGeneric.mustache b/generation/templates/modelGeneric.mustache new file mode 100644 index 00000000..432b6e34 --- /dev/null +++ b/generation/templates/modelGeneric.mustache @@ -0,0 +1,426 @@ + /// + /// {{description}}{{^description}}{{classname}}{{/description}} + /// + {{#vendorExtensions.x-cls-compliant}} + [CLSCompliant({{{vendorExtensions.x-cls-compliant}}})] + {{/vendorExtensions.x-cls-compliant}} + {{#vendorExtensions.x-com-visible}} + [ComVisible({{{vendorExtensions.x-com-visible}}})] + {{/vendorExtensions.x-com-visible}} + [DataContract(Name = "{{{name}}}")] + {{^useUnityWebRequest}} + {{#discriminator}} + [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")] + {{#mappedModels}} + [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] + {{/mappedModels}} + {{/discriminator}} + {{/useUnityWebRequest}} + {{>visibility}} partial class {{classname}}{{#lambda.firstDot}}{{#parent}} : .{{/parent}}{{#validatable}} : .{{/validatable}}{{#equatable}} : .{{/equatable}}{{/lambda.firstDot}}{{#lambda.joinWithComma}}{{#parent}}{{{.}}} {{/parent}}{{#equatable}}IEquatable<{{classname}}> {{/equatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + { + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/isEnum}} + {{#isEnum}} + + /// + /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#example}} + /// {{.}} + {{/example}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + {{#isReadOnly}} + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + + {{^isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/vars}} + {{#hasRequired}} + {{^hasOnlyReadOnly}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + {{^isAdditionalPropertiesTrue}} + protected {{classname}}() { } + {{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + protected {{classname}}() + { + this.AdditionalProperties = new Dictionary(); + } + {{/isAdditionalPropertiesTrue}} + {{/hasOnlyReadOnly}} + {{/hasRequired}} + /// + /// Initializes a new instance of the class. + /// + {{#readWriteVars}} + /// {{description}}{{^description}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}. + {{/readWriteVars}} + {{#hasOnlyReadOnly}} + [JsonConstructorAttribute] + {{/hasOnlyReadOnly}} + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{#defaultValue}}{{^isDateTime}}{{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default({{{datatypeWithEnum}}}){{/isDateTime}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{^-last}}, {{/-last}}{{/parentVars}}){{/parent}} + { + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{#required}} + {{^conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}" is required (not null) + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} == null) + { + throw new ArgumentNullException("{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} is a required property for {{classname}} and cannot be null"); + } + this.{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}" is required (not null) + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} == null) + { + throw new ArgumentNullException("{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} is a required property for {{classname}} and cannot be null"); + } + this._{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this._{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{^required}} + {{#defaultValue}} + {{^conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // use default value if no "{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}" provided + this.{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} ?? {{#isString}}@{{/isString}}{{{defaultValue}}}; + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{/defaultValue}} + {{^defaultValue}} + {{^conditionalSerialization}} + this.{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + {{/conditionalSerialization}} + {{#conditionalSerialization}} + this._{{name}} = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}; + if (this.{{name}} != null) + { + this._flag{{name}} = true; + } + {{/conditionalSerialization}} + {{/defaultValue}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + this.AdditionalProperties = new Dictionary(); + {{/isAdditionalPropertiesTrue}} + } + + {{#vars}} + {{^isInherited}} + {{^isEnum}} + /// + /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /// {{.}} + {{/example}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + {{^supportsDateOnly}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/supportsDateOnly}} + {{/isDate}} + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + + {{#isReadOnly}} + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{dataType}}} {{name}} { get; private set; } + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{^isReadOnly}} + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] + {{#deprecated}} + [Obsolete] + {{/deprecated}} + public {{{dataType}}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{{dataType}}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + {{/isAdditionalPropertiesTrue}} + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#parent}} + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + {{/parent}} + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + {{#isAdditionalPropertiesTrue}} + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + {{/isAdditionalPropertiesTrue}} + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public {{#parent}}{{^isArray}}{{^isMap}}override {{/isMap}}{{/isArray}}{{/parent}}{{^parent}}virtual {{/parent}}string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + {{#equatable}} + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + { + return false; + } + return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}} + (this.{{name}} != null && + this.{{name}}.Equals(input.{{name}})) + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + this.{{name}}.Equals(input.{{name}}) + {{/vendorExtensions.x-is-value-type}} + ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}this.{{name}} != null && + input.{{name}} != null && + {{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); + {{/isAdditionalPropertiesTrue}} + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + {{#parent}} + int hashCode = base.GetHashCode(); + {{/parent}} + {{^parent}} + int hashCode = 41; + {{/parent}} + {{#vars}} + {{^vendorExtensions.x-is-value-type}} + if (this.{{name}} != null) + { + hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); + } + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); + {{/vendorExtensions.x-is-value-type}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + {{/isAdditionalPropertiesTrue}} + return hashCode; + } + } + {{/equatable}} + +{{#validatable}} +{{>validatable}} +{{/validatable}} + } diff --git a/generation/templates/modelInnerEnum.mustache b/generation/templates/modelInnerEnum.mustache new file mode 100644 index 00000000..462ded84 --- /dev/null +++ b/generation/templates/modelInnerEnum.mustache @@ -0,0 +1,99 @@ + {{^isContainer}} + /// + /// {{description}}{{^description}}Defines {{{name}}}{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#isString}} + {{^useGenericHost}} + [JsonConverter(typeof(StringEnumConverter))] + {{/useGenericHost}} + {{/isString}} + {{>visibility}} enum {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{value}} + /// + {{^useGenericHost}} + {{#isString}} + [EnumMember(Value = "{{{value}}}")] + {{/isString}} + {{/useGenericHost}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}}{{^vendorExtensions.x-zero-based-enum}} = {{-index}}{{/vendorExtensions.x-zero-based-enum}}{{/isString}}{{^-last}},{{/-last}} + {{^-last}} + + {{/-last}} + {{/enumVars}} + {{/allowableValues}} + } + {{#useGenericHost}} + + /// + /// Returns a + /// + /// + /// + /// + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}FromString(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value.Equals({{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}})) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Could not convert value to type {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}FromStringOrDefault(string value) + { + {{#allowableValues}} + {{#enumVars}} + if (value.Equals({{^isString}}({{{value}}}).ToString(){{/isString}}{{#isString}}"{{{value}}}"{{/isString}})) + return {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}; + + {{/enumVars}} + {{/allowableValues}} + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + {{#isString}} + /// + {{/isString}} + public static {{>EnumValueDataType}}{{#lambda.first}}{{#nrt}}{{#isString}}{{#isNullable}}{{nrt?}} {{^nrt}}{{#vendorExtensions.x-is-value-type}}? {{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}}{{/isString}}{{/nrt}}{{/lambda.first}} {{datatypeWithEnum}}ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#isString}}{{>NullConditionalProperty}}{{/isString}} value) + { + {{^isString}} + return ({{>EnumValueDataType}}) value; + {{/isString}} + {{#isString}} + {{#isNullable}} + if (value == null) + return null; + + {{/isNullable}} + {{#allowableValues}} + {{#enumVars}} + if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}) + return {{^isNumeric}}"{{/isNumeric}}{{{value}}}{{^isNumeric}}"{{/isNumeric}}; + + {{/enumVars}} + {{/allowableValues}} + throw new NotImplementedException($"Value could not be handled: '{value}'"); + {{/isString}} + } + {{/useGenericHost}} + {{/isContainer}} \ No newline at end of file diff --git a/generation/templates/modelOneOf.mustache b/generation/templates/modelOneOf.mustache new file mode 100644 index 00000000..ab42e4ee --- /dev/null +++ b/generation/templates/modelOneOf.mustache @@ -0,0 +1,320 @@ +{{#model}} + /// + /// {{description}}{{^description}}{{classname}}{{/description}} + /// + {{#vendorExtensions.x-cls-compliant}} + [CLSCompliant({{{.}}})] + {{/vendorExtensions.x-cls-compliant}} + {{#vendorExtensions.x-com-visible}} + [ComVisible({{{.}}})] + {{/vendorExtensions.x-com-visible}} + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : {{#lambda.joinWithComma}}AbstractOpenAPISchema {{#parent}}{{{.}}} {{/parent}}{{#equatable}}IEquatable<{{classname}}> {{/equatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + {{/isNullable}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^isNull}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{dataType}}. + public {{classname}}({{{dataType}}} actualInstance) + { + this.IsNullable = {{#model.isNullable}}true{{/model.isNullable}}{{^model.isNullable}}false{{/model.isNullable}}; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance{{^model.isNullable}}{{^isPrimitiveType}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isPrimitiveType}}{{#isPrimitiveType}}{{#isArray}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isArray}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isFreeFormObject}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isString}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isString}}{{/isPrimitiveType}}{{/model.isNullable}}; + } + + {{/isNull}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#oneOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}}) || value is {{{.}}}) + { + this._actualInstance = value; + } + {{/oneOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#oneOf}} {{{.}}}{{^-last}},{{/-last}}{{/oneOf}}"); + } + } + } + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^isNull}} + + /// + /// Get the actual instance of `{{dataType}}`. If the actual instance is not `{{dataType}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{dataType}} + public {{{dataType}}} Get{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{#isArray}}{{#lambda.titlecase}}{{{dataFormat}}}{{/lambda.titlecase}}{{/isArray}}() + { + return ({{{dataType}}})this.ActualInstance; + } + {{/isNull}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return new{{classname}}; + } + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + + try + { + var discriminatorObj = JObject.Parse(jsonString)["{{{propertyBaseName}}}"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + {{#mappedModels}} + case "{{{mappingName}}}": + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{modelName}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + return new{{classname}}; + {{/mappedModels}} + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + List matchedTypes = new List(); + {{#oneOf}} + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof({{{.}}}).GetProperty("AdditionalProperties") == null) + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + } + else + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("{{{.}}}"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/oneOf}} + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + String.Join(",", matchedTypes)); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + + {{#equatable}} + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return this.ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + {{/equatable}} + {{#validatable}} + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + {{/validatable}} + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + switch(reader.TokenType) + { + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{#isInteger}} + case JsonToken.Integer: + return new {{classname}}(Convert.ToInt32(reader.Value)); + {{/isInteger}} + {{#isNumber}} + case JsonToken.Float: + return new {{classname}}(Convert.ToDecimal(reader.Value)); + {{/isNumber}} + {{#isString}} + case JsonToken.String: + return new {{classname}}(Convert.ToString(reader.Value)); + {{/isString}} + {{#isBoolean}} + case JsonToken.Boolean: + return new {{classname}}(Convert.ToBoolean(reader.Value)); + {{/isBoolean}} + {{#isDate}} + case JsonToken.Date: + return new {{classname}}(Convert.ToDateTime(reader.Value)); + {{/isDate}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + case JsonToken.StartObject: + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + case JsonToken.StartArray: + return {{classname}}.FromJson(JArray.Load(reader).ToString(Formatting.None)); + default: + return null; + } + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } +{{/model}} diff --git a/generation/templates/model_doc.mustache b/generation/templates/model_doc.mustache new file mode 100644 index 00000000..3c7f8b2d --- /dev/null +++ b/generation/templates/model_doc.mustache @@ -0,0 +1,22 @@ +{{#models}} +{{#model}} +# {{{packageName}}}.{{modelPackage}}.{{{classname}}} +{{#description}}{{&description}} +{{/description}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#parent}} +{{#parentVars}} +**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/parentVars}} +{{/parent}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../{{#useGenericHost}}../{{/useGenericHost}}README.md#documentation-for-models) [[Back to API list]](../{{#useGenericHost}}../{{/useGenericHost}}README.md#documentation-for-api-endpoints) [[Back to README]](../{{#useGenericHost}}../{{/useGenericHost}}README.md) + +{{/model}} +{{/models}} diff --git a/generation/templates/model_test.mustache b/generation/templates/model_test.mustache new file mode 100644 index 00000000..1feaeb9d --- /dev/null +++ b/generation/templates/model_test.mustache @@ -0,0 +1,87 @@ +{{>partial_header}} + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.{{clientPackage}}; +using System.Reflection; +{{^useGenericHost}} +using Newtonsoft.Json; +{{/useGenericHost}} + +{{#models}} +{{#model}} +namespace {{packageName}}.Test.Model +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class {{classname}}Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; + + public {{classname}}Tests() + { + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{classname}}InstanceTest() + { + // TODO uncomment below to test "IsType" {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + + {{#discriminator}} + {{#children}} + + /// + /// Test deserialize a {{classname}} from type {{parent}} + /// + [Fact] + public void {{classname}}DeserializeFrom{{parent}}Test() + { + // TODO uncomment below to test deserialize a {{classname}} from type {{parent}} + //Assert.IsType<{{parent}}>(JsonConvert.DeserializeObject<{{parent}}>(new {{classname}}().ToJson())); + } + + {{/children}} + {{/discriminator}} + {{#vars}} + + + /// + /// Test the property '{{name}}' + /// + [Fact] + public void {{name}}Test() + { + // TODO unit test for the property '{{name}}' + } + {{/vars}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } +} +{{/model}} +{{/models}} diff --git a/generation/templates/netcore_project.additions.mustache b/generation/templates/netcore_project.additions.mustache new file mode 100644 index 00000000..8c6f3ad5 --- /dev/null +++ b/generation/templates/netcore_project.additions.mustache @@ -0,0 +1 @@ +{{! if needed users can add this file to their templates folder to append to the csproj }} \ No newline at end of file diff --git a/generation/templates/netcore_project.mustache b/generation/templates/netcore_project.mustache new file mode 100644 index 00000000..7dd6228f --- /dev/null +++ b/generation/templates/netcore_project.mustache @@ -0,0 +1,84 @@ + + + {{#useGenericHost}} + true {{/useGenericHost}}{{^useGenericHost}} + false{{/useGenericHost}} + {{targetFramework}} + {{packageName}} + {{packageName}} + Library + {{packageAuthors}} + {{packageCompany}} + {{packageTitle}} + {{packageDescription}} + {{packageCopyright}} + {{packageName}} + {{packageVersion}} + bin\$(Configuration)\$(TargetFramework)\{{packageName}}.xml{{#licenseId}} + {{.}}{{/licenseId}} + https://{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}.git + git{{#releaseNote}} + {{.}}{{/releaseNote}}{{#packageTags}} + {{{.}}}{{/packageTags}}{{#nrt}} + {{#useGenericHost}}enable{{/useGenericHost}}{{^useGenericHost}}annotations{{/useGenericHost}}{{/nrt}} + false + + + + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + {{^useGenericHost}} + + + {{/useGenericHost}} + {{#useRestSharp}} + + {{/useRestSharp}} + {{#useGenericHost}} + + + {{#supportsRetry}} + + {{/supportsRetry}} + {{#net80OrLater}} + + {{/net80OrLater}} + {{^net60OrLater}} + + {{#net47OrLater}} + + {{/net47OrLater}} + {{/net60OrLater}} + {{/useGenericHost}} + {{^useGenericHost}} + {{#supportsRetry}} + + {{/supportsRetry}} + {{/useGenericHost}} + {{#validatable}} + {{^net60OrLater}} + + {{/net60OrLater}} + {{/validatable}} + + +{{^useGenericHost}} + + {{^net60OrLater}} + + {{/net60OrLater}} + {{#net48}} + + {{/net48}} + + + {{^net60OrLater}} + + {{/net60OrLater}} + {{#net48}} + + {{/net48}} + +{{/useGenericHost}} +{{>netcore_project.additions}} diff --git a/generation/templates/netcore_testproject.additions.mustache b/generation/templates/netcore_testproject.additions.mustache new file mode 100644 index 00000000..8c6f3ad5 --- /dev/null +++ b/generation/templates/netcore_testproject.additions.mustache @@ -0,0 +1 @@ +{{! if needed users can add this file to their templates folder to append to the csproj }} \ No newline at end of file diff --git a/generation/templates/netcore_testproject.mustache b/generation/templates/netcore_testproject.mustache new file mode 100644 index 00000000..90d11eb8 --- /dev/null +++ b/generation/templates/netcore_testproject.mustache @@ -0,0 +1,20 @@ + + + + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false{{#nrt}} + {{#useGenericHost}}enable{{/useGenericHost}}{{^useGenericHost}}annotations{{/useGenericHost}}{{/nrt}} + + + + + + + + + + + +{{>netcore_testproject.additions}} diff --git a/generation/templates/nuspec.mustache b/generation/templates/nuspec.mustache new file mode 100644 index 00000000..18fe4aac --- /dev/null +++ b/generation/templates/nuspec.mustache @@ -0,0 +1,57 @@ + + + + + $id$ + {{packageTitle}} + + + $version$ + + + $author$ + + + $author$ + false + false + + + {{packageDescription}} + {{#termsOfService}} + {{.}} + {{/termsOfService}} + {{#licenseUrl}} + {{.}} + {{/licenseUrl}} + + + + + + {{#useRestSharp}} + + {{/useRestSharp}} + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + + {{#validatable}} + + {{/validatable}} + {{#supportsRetry}} + + {{/supportsRetry}} + + + + + + + + + + + diff --git a/generation/templates/openapi.mustache b/generation/templates/openapi.mustache new file mode 100644 index 00000000..34fbb53f --- /dev/null +++ b/generation/templates/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} diff --git a/generation/templates/partial_header.mustache b/generation/templates/partial_header.mustache new file mode 100644 index 00000000..1562058a --- /dev/null +++ b/generation/templates/partial_header.mustache @@ -0,0 +1,17 @@ +/* + {{#appName}} + * {{{.}}} + * + {{/appName}} + {{#appDescription}} + * {{{.}}} + * + {{/appDescription}} + {{#version}} + * The version of the OpenAPI document: {{{.}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{.}}} + {{/infoEmail}} + * Generated by: https://github.com/openapitools/openapi-generator.git + */ diff --git a/generation/templates/validatable.mustache b/generation/templates/validatable.mustache new file mode 100644 index 00000000..a79db1a6 --- /dev/null +++ b/generation/templates/validatable.mustache @@ -0,0 +1,135 @@ +{{#discriminator}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { +{{/discriminator}} +{{^discriminator}} + {{#parent}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + {{/parent}} + {{^parent}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + {{/parent}} +{{/discriminator}} + {{#parent}} + {{^isArray}} + {{^isMap}} + foreach (var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext)) + { + yield return x; + } + {{/isMap}} + {{/isArray}} + {{/parent}} + {{#vars}} + {{#hasValidation}} + {{^isEnum}} + {{#maxLength}} + // {{{name}}} ({{{dataType}}}) maxLength + if (this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } + + {{/maxLength}} + {{#minLength}} + // {{{name}}} ({{{dataType}}}) minLength + if (this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } + + {{/minLength}} + {{#maximum}} + // {{{name}}} ({{{dataType}}}) maximum + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} > ({{{dataType}}}){{maximum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); + } + + {{/maximum}} + {{#minimum}} + // {{{name}}} ({{{dataType}}}) minimum + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} < ({{{dataType}}}){{minimum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); + } + + {{/minimum}} + {{#pattern}} + {{^isByteArray}} + {{#vendorExtensions.x-is-value-type}} + {{#isNullable}} + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null){ + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>ValidateRegex}} + {{/lambda.indent4}} + + {{/lambda.trimTrailingWithNewLine}} + } + + {{/isNullable}} + {{^isNullable}} + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent3}} + {{>ValidateRegex}} + {{/lambda.indent3}} + + {{/lambda.trimTrailingWithNewLine}} + {{/isNullable}} + {{/vendorExtensions.x-is-value-type}} + {{^vendorExtensions.x-is-value-type}} + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null) { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>ValidateRegex}} + {{/lambda.indent4}} + + {{/lambda.trimTrailingWithNewLine}} + } + + {{/vendorExtensions.x-is-value-type}} + {{/isByteArray}} + {{/pattern}} + {{/isEnum}} + {{/hasValidation}} + {{/vars}} + yield break; + } \ No newline at end of file diff --git a/generation/templates/visibility.mustache b/generation/templates/visibility.mustache new file mode 100644 index 00000000..a1d1f416 --- /dev/null +++ b/generation/templates/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/openapitools.json b/openapitools.json new file mode 100644 index 00000000..f227cf2d --- /dev/null +++ b/openapitools.json @@ -0,0 +1,7 @@ +{ + "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "7.7.0" + } +}