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

csharp.ClientUtils.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
{{>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);
{{#net60OrLater}}
            if (obj is DateOnly dateOnly)
                // 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-15
                return dateOnly.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
{{/net60OrLater}}
            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(global::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;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy