ConfigurationHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using EasyDevCore.Common;
  2. using EasyDevCore.Configuration.Configuration;
  3. using Microsoft.Extensions.Configuration;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml.Linq;
  12. namespace EasyDevCore.Configuration
  13. {
  14. /// <summary>
  15. ///
  16. /// </summary>
  17. public static class ConfigurationHelper
  18. {
  19. /// <summary>
  20. /// Gets the configuation root.
  21. /// </summary>
  22. /// <param name="section">The section.</param>
  23. /// <returns></returns>
  24. public static IConfigurationRoot GetConfiguationRoot(this IConfiguration section)
  25. {
  26. if (section is IConfigurationRoot)
  27. {
  28. return (IConfigurationRoot)section;
  29. }
  30. else
  31. {
  32. var fieldInfo = section.GetType().GetField("_root", BindingFlags.NonPublic | BindingFlags.Instance);
  33. var root = fieldInfo.GetValue(section);
  34. return (IConfigurationRoot)root;
  35. }
  36. }
  37. /// <summary>
  38. /// Gets the application setting constants.
  39. /// </summary>
  40. /// <param name="configurationRoot">The configuration root.</param>
  41. /// <returns></returns>
  42. public static Dictionary<string, string> GetAppSettingConstants(this IConfigurationRoot configurationRoot)
  43. {
  44. var appContantsSection = configurationRoot.GetSection("AppSetting:Constants");
  45. var envContantsSection = appContantsSection.GetSection("HOST-ENVIROMENT-VARIABLE");
  46. Dictionary<string, string> result = new();
  47. foreach (var kp in appContantsSection.GetChildren().Where(kp => !kp.Key.Equals("HOST-ENVIROMENT-VARIABLE", StringComparison.InvariantCultureIgnoreCase)))
  48. {
  49. result[kp.Key] = kp.Value;
  50. }
  51. foreach (var kp in envContantsSection.GetChildren())
  52. {
  53. bool isPrefer = kp.Key.StartsWith("!");
  54. string key = isPrefer ? kp.Key.Substring(1) : kp.Key;
  55. string envValue = null;
  56. if (!result.ContainsKey(key) || isPrefer)
  57. {
  58. envValue = Environment.GetEnvironmentVariable(kp.Value);
  59. }
  60. if (envValue != null)
  61. {
  62. result[key] = envValue;
  63. }
  64. }
  65. return result;
  66. }
  67. /// <summary>
  68. /// Maps the application setting contants.
  69. /// </summary>
  70. /// <param name="builder">The builder.</param>
  71. /// <returns></returns>
  72. public static IConfigurationBuilder MapAppSettingContants(this IConfigurationBuilder builder)
  73. {
  74. var root = (builder as IConfigurationRoot);
  75. var appContantsSection = root.GetSection("AppSettings:Constants");
  76. Dictionary<string, string> constValues = new();
  77. foreach (var kp in appContantsSection.GetChildren().Where(x => !string.IsNullOrWhiteSpace(x.Value)))
  78. {
  79. constValues[kp.Key] = kp.Value;
  80. }
  81. List<string> placeHolders = new();
  82. foreach (var kp in root.GetAllChildren().Where(x => !string.IsNullOrWhiteSpace(x.Value) && x.Value.Contains("{{") && x.Value.Contains("}}")))
  83. {
  84. placeHolders.Clear();
  85. kp.Value.RegexGroupMatch(@"\{\{(?<V>[^{}].*?)\}\}", (g) =>
  86. {
  87. if(constValues.ContainsKey(g.Value))
  88. {
  89. placeHolders.Add(g.Value);
  90. }
  91. });
  92. foreach(var p in placeHolders)
  93. {
  94. kp.Value = kp.Value.Replace("{{" + p + "}}", constValues[p]);
  95. }
  96. }
  97. return builder;
  98. }
  99. /// <summary>
  100. /// Gets the application setting constants.
  101. /// </summary>
  102. /// <param name="configurationRoot">The configuration root.</param>
  103. /// <returns></returns>
  104. public static Dictionary<string, string> GetAppSettingEnvConstants(this IConfigurationRoot configurationRoot)
  105. {
  106. Dictionary<string, string> result = new Dictionary<string, string>();
  107. foreach (var kp in configurationRoot.GetSection("AppSetting:Constants:HOST-ENVIROMENT-VARIABLE").GetChildren())
  108. {
  109. result.Add(kp.Key, kp.Value);
  110. }
  111. return result;
  112. }
  113. /// <summary>
  114. /// Gets the configuration section.
  115. /// </summary>
  116. /// <param name="configuration">The configuration.</param>
  117. /// <param name="sectionName">Name of the section.</param>
  118. /// <returns></returns>
  119. public static IConfigurationSection GetConfigMapEnvVariableSection(this IConfiguration configuration, string sectionName) => new EasyConfigurationSection(configuration.GetSection(sectionName));
  120. /// <summary>
  121. /// Binds the configuration value.
  122. /// </summary>
  123. /// <typeparam name="TModel">The type of the model.</typeparam>
  124. /// <param name="section">The section.</param>
  125. /// <param name="sectionName">Name of the section.</param>
  126. /// <returns></returns>
  127. public static TModel BindConfigEnvVariable<TModel>(this IConfiguration section, string sectionName) where TModel : class
  128. {
  129. return section.GetConfigMapEnvVariableSection(sectionName).Bind<TModel>();
  130. }
  131. private static string GetEnvironmentVariable(string key)
  132. {
  133. return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Process)
  134. ?? Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User)
  135. ?? Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Machine);
  136. }
  137. /// <summary>
  138. /// Translates the configuration value with enviroment macro.
  139. /// </summary>
  140. /// <param name="section">The section.</param>
  141. /// <param name="value">The value.</param>
  142. /// <param name="defaultValue">The default value.</param>
  143. /// <returns></returns>
  144. public static T ResolveConfigVariable<T>(this IConfiguration section, string value, T defaultValue = default(T))
  145. {
  146. var root = section.GetConfiguationRoot();
  147. var appContantsSection = root.GetSection("AppSettings:Constants");
  148. var envContantsSection = appContantsSection.GetSection("HOST-ENVIROMENT-VARIABLE");
  149. Dictionary<string, string> appContants = new();
  150. value.RegexGroupMatch(@"\{\{(.*?)\}\}", (m) =>
  151. {
  152. try
  153. {
  154. string appValue = appContantsSection.GetValue<string>(m.Value);
  155. string envValueKey = envContantsSection.GetValue<string>(m.Value);
  156. string preferEnvKey = envContantsSection.GetValue<string>("!" + m.Value);
  157. string replaceValue = (preferEnvKey == null ? null : GetEnvironmentVariable(preferEnvKey)) ?? appValue ?? (envValueKey == null ? null : GetEnvironmentVariable(envValueKey));
  158. if (replaceValue != null)
  159. {
  160. appContants[m.Value] = replaceValue;
  161. }
  162. }
  163. catch { }
  164. });
  165. foreach (var kp in appContants)
  166. {
  167. value = value.Replace(kp.Key, kp.Value);
  168. }
  169. if (defaultValue == null)
  170. {
  171. return value.ConvertTo<T>();
  172. }
  173. else
  174. {
  175. return value.ConvertTo<T>(defaultValue);
  176. }
  177. }
  178. /// <summary>
  179. /// Gets configuration value and auto substitute with constants.
  180. /// </summary>
  181. /// <typeparam name="T"></typeparam>
  182. /// <param name="section">The section.</param>
  183. /// <param name="key">The key.</param>
  184. /// <param name="defaultValue">The default value.</param>
  185. /// <returns></returns>
  186. public static T GetConfigMapVariable<T>(this IConfiguration section, string key, T defaultValue = default(T))
  187. {
  188. return ResolveConfigVariable<T>(section, section.GetSection(key).Value, defaultValue);
  189. }
  190. /// <summary>
  191. /// Binds the specified section.
  192. /// </summary>
  193. /// <typeparam name="T"></typeparam>
  194. /// <param name="section">The section.</param>
  195. /// <returns></returns>
  196. /// <exception cref="ConfigurationErrorsException">
  197. /// </exception>
  198. public static T Bind<T>(this IConfigurationSection section)
  199. {
  200. try
  201. {
  202. if (section.Value != null)
  203. return section.Value.ConvertTo<T>();
  204. if (typeof(T).HasInterface<IEnumerable>()
  205. && !typeof(T).HasInterface<IDictionary>())
  206. {
  207. var values = section.GetChildren().Map(GetValue);
  208. return values.ConvertTo<T>();
  209. }
  210. }
  211. catch (Exception ex)
  212. {
  213. var message = $"The {section.Key} setting had an invalid format. " +
  214. $"The value \"{section.Value}\" could not be cast to type {typeof(T).FullName}";
  215. throw new ConfigurationErrorsException(message, ex);
  216. }
  217. try
  218. {
  219. var to = typeof(T).CreateInstance();
  220. section.Bind(to);
  221. return (T)to;
  222. }
  223. catch (InvalidOperationException ex)
  224. {
  225. throw new ConfigurationErrorsException(ex.Message, ex);
  226. }
  227. }
  228. /// <summary>
  229. /// Binds the specified section name.
  230. /// </summary>
  231. /// <typeparam name="T"></typeparam>
  232. /// <param name="config">The configuration.</param>
  233. /// <param name="sectionName">Name of the section.</param>
  234. /// <returns></returns>
  235. public static T Bind<T>(this IConfiguration config, string sectionName = null) => Bind<T>(config.GetSection(sectionName ?? typeof(T).Name));
  236. /// <summary>
  237. /// Existses the specified key.
  238. /// </summary>
  239. /// <param name="section">The section.</param>
  240. /// <param name="key">The key.</param>
  241. /// <returns></returns>
  242. public static bool Exists(this IConfigurationSection section, string key) => section.GetChildren().Any(x => x.Key == key) || section.GetSection(key).Exists();
  243. /// <summary>
  244. /// Existses the specified key.
  245. /// </summary>
  246. /// <param name="config">The configuration.</param>
  247. /// <param name="key">The key.</param>
  248. /// <returns></returns>
  249. public static bool Exists(this IConfiguration config, string key) => config.GetChildren().Any(x => x.Key == key) || config.GetSection(key).Exists();
  250. private static void GetAllChildren(List<IConfigurationSection> list, IConfiguration config)
  251. {
  252. foreach(var item in config.GetChildren())
  253. {
  254. if (item is IConfigurationSection) list.Add(item);
  255. GetAllChildren(list, item);
  256. }
  257. }
  258. /// <summary>
  259. /// Gets all children.
  260. /// </summary>
  261. /// <param name="configuration">The configuration.</param>
  262. /// <returns></returns>
  263. public static IEnumerable<IConfigurationSection> GetAllChildren(this IConfiguration configuration)
  264. {
  265. List<IConfigurationSection> list = new();
  266. GetAllChildren(list, configuration);
  267. return list;
  268. }
  269. /// <summary>Gets the value.</summary>
  270. /// <param name="section">The section.</param>
  271. /// <returns>
  272. /// <br />
  273. /// </returns>
  274. static object GetValue(this IConfigurationSection section)
  275. {
  276. if (section == null)
  277. return null;
  278. if (section.Value != null)
  279. return section.Value;
  280. var children = section.GetChildren();
  281. var first = children.FirstOrDefault();
  282. if (first == null)
  283. return null;
  284. if (first.Key == "0")
  285. {
  286. var to = children.Select(GetValue).ToList();
  287. if (to.Count > 0)
  288. return to;
  289. }
  290. else
  291. {
  292. var to = new Dictionary<string, object>();
  293. foreach (var child in children)
  294. {
  295. to[child.Key] = GetValue(child);
  296. }
  297. if (to.Count > 0)
  298. return to;
  299. }
  300. return null;
  301. }
  302. }
  303. }