using EasyDevCore.Common;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyDevCore.Configuration.Configuration
{
///
///
///
public static class EasyConfigurationExtensions
{
///
/// Resolves the macro value (like pattern {Property}) from config file.
///
/// The configuration.
/// The configuration secrets.
/// Name of the section.
/// if set to true [resolve children].
///
public static IConfiguration ResolveConfigSecrets(this IConfiguration config, EasyConfiguration configSecrets, string sectionName = "", bool resolveChildren = true)
{
var section = config;
if (!string.IsNullOrWhiteSpace(sectionName))
{
section = config.GetSection(sectionName);
}
var list = resolveChildren ? section.GetAllChildren() : section.GetChildren();
foreach(var item in list)
{
var value = item.Value;
var found = BindSecretItem(configSecrets, ref value);
if (found)
{
item.Value = value;
}
}
return config;
}
///
/// Binds the secret item.
///
/// The configuration secrets.
/// The configuration string.
///
private static bool BindSecretItem(EasyConfiguration configSecrets, ref string configString)
{
var decodedValue = configString;
var found = false;
if (configString == null) return false;
configString.RegexGroupMatch("{(?[^{}]+)}", (m) =>
{
if (m.Value == "m" && configSecrets.Exists(m.Value))
{
found = true;
decodedValue = decodedValue.Replace("{{" + m.Value + "}}", (configSecrets[m.Value] ?? "?Null?").ToString(), StringComparison.InvariantCultureIgnoreCase);
}
});
if (found)
{
configString = decodedValue;
}
return found;
}
///
/// Resolves the secret item.
///
/// The configuration secrets.
/// The configuration string.
///
public static string ResolveSecretItem(this EasyConfiguration configSecrets, string configString)
{
BindSecretItem(configSecrets, ref configString);
return configString;
}
}
}