All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp.Configuration.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
{{>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
        /// 
        [global::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 = TimeSpan.FromSeconds(100);
        }

        /// 
        /// Initializes a new instance of the  class
        /// 
        [global::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 of ApiClient. Defaults to 100 seconds.
        /// 
        public virtual TimeSpan 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 client scope for OAuth2 authentication.
        /// 
        /// The OAuth Client Scope.
        public virtual string{{nrt?}} OAuthScope { 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,
                OAuthScope = second.OAuthScope ?? first.OAuthScope,
                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
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy