diff --git a/Extensions/IConfigurationExtensions.cs b/Extensions/IConfigurationExtensions.cs index 58533e9..d3562a9 100644 --- a/Extensions/IConfigurationExtensions.cs +++ b/Extensions/IConfigurationExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Configuration; using xCommons.Configurations; using xCommons.Constants; @@ -49,5 +50,130 @@ namespace xCommons.Extensions .GetSection(ConfigurationNodeNames.SWAGGER_NODE); return xSwaggerConfigSection.Get(); } + + /// + /// Converts a ConfigurationSection to object Representation ... + /// + /// + /// + public static object ToObject(this IConfigurationSection section) + { + // + // an Inner Function for Create Recursive Parsing ... + object ConvertSection(IConfigurationSection sec) + { + // + var children = sec + .GetChildren() + .ToList(); + if (!children.Any()) + { + return sec.Value ?? string.Empty; + } + + // + // Detect Array Like Sections ... + bool isArray = children.All(ch => int.TryParse(ch.Key, out _)); + if (isArray) + { + // + return children + .OrderBy(c => int.Parse(c.Key)) + .Select(ConvertSection) + .ToList(); + } + + // + // Otherwise ... + return children + .ToDictionary( + c => c.Key, + c => ConvertSection(c) + ); + } + + // + // Try to Parse using Inner Function ... + var result = ConvertSection(section); + + // + return result; + } + + /// + /// Converts a ConfigurationSection to Json Representation ... + /// + /// + /// + public static string ToJSON(this IConfigurationSection section) + { + // + // Try to Parse using Inner Function ... + var obj = section.ToObject(); + + // + // Convert it to Json ... + var result = obj.ToJSON(); + + // + return result; + } + + /// + /// Get a Configuration Section as Object ... + /// + /// + /// + /// + public static object GetSectionAsObject( + this IConfiguration source, + string section + ) + { + // + object result = null; + + // + if (!section.IsNullOrEmpty()) + { + // + var sec = source.GetSection(section); + if (!sec.IsNull()) + { + result = sec.ToObject(); + } + } + + // + return result; + } + + /// + /// Retrieve a Configuration Section as Json String ... + /// + /// + /// + /// + public static string GetSectionAsJson( + this IConfiguration source, + string section + ) + { + // + var result = string.Empty; + + // + // Retrieve Secion as Object ... + var obj = source.GetSectionAsObject(section); + if (!obj.IsNull()) + { + // + // Converts Section Object to Json ... + result = obj.ToJSON(); + } + + // + return result; + } } } \ No newline at end of file