ConfigurationManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. global using static Terminal.Gui.ConfigurationManager;
  2. global using CM = Terminal.Gui.ConfigurationManager;
  3. using System.Collections;
  4. using System.Diagnostics;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Reflection;
  7. using System.Runtime.Versioning;
  8. using System.Text.Encodings.Web;
  9. using System.Text.Json;
  10. using System.Text.Json.Serialization;
  11. #nullable enable
  12. namespace Terminal.Gui;
  13. /// <summary>
  14. /// Provides settings and configuration management for Terminal.Gui applications.
  15. /// <para>
  16. /// Users can set Terminal.Gui settings on a global or per-application basis by providing JSON formatted
  17. /// configuration files. The configuration files can be placed in at <c>.tui</c> folder in the user's home
  18. /// directory (e.g. <c>C:/Users/username/.tui</c>, or <c>/usr/username/.tui</c>), the folder where the Terminal.Gui
  19. /// application was launched from (e.g. <c>./.tui</c> ), or as a resource within the Terminal.Gui application's
  20. /// main assembly.
  21. /// </para>
  22. /// <para>
  23. /// Settings are defined in JSON format, according to this schema:
  24. /// https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json
  25. /// </para>
  26. /// <para>
  27. /// Settings that will apply to all applications (global settings) reside in files named <c>config.json</c>.
  28. /// Settings that will apply to a specific Terminal.Gui application reside in files named
  29. /// <c>appname.config.json</c>, where <c>appname</c> is the assembly name of the application (e.g.
  30. /// <c>UICatalog.config.json</c>).
  31. /// </para>
  32. /// Settings are applied using the following precedence (higher precedence settings overwrite lower precedence
  33. /// settings):
  34. /// <para>
  35. /// 1. Application configuration found in the users' home directory (<c>~/.tui/appname.config.json</c>) --
  36. /// Highest precedence
  37. /// </para>
  38. /// <para>
  39. /// 2. Application configuration found in the directory the app was launched from (
  40. /// <c>./.tui/appname.config.json</c>).
  41. /// </para>
  42. /// <para>3. Application configuration found in the applications' resources (<c>Resources/config.json</c>).</para>
  43. /// <para>4. Global configuration found in the user's home directory (<c>~/.tui/config.json</c>).</para>
  44. /// <para>5. Global configuration found in the directory the app was launched from (<c>./.tui/config.json</c>).</para>
  45. /// <para>
  46. /// 6. Global configuration in <c>Terminal.Gui.dll</c>'s resources (<c>Terminal.Gui.Resources.config.json</c>) --
  47. /// Lowest Precedence.
  48. /// </para>
  49. /// </summary>
  50. [ComponentGuarantees (ComponentGuaranteesOptions.None)]
  51. public static class ConfigurationManager
  52. {
  53. /// <summary>
  54. /// A dictionary of all properties in the Terminal.Gui project that are decorated with the
  55. /// <see cref="SerializableConfigurationProperty"/> attribute. The keys are the property names pre-pended with the
  56. /// class that implements the property (e.g. <c>Application.UseSystemConsole</c>). The values are instances of
  57. /// <see cref="ConfigProperty"/> which hold the property's value and the <see cref="PropertyInfo"/> that allows
  58. /// <see cref="ConfigurationManager"/> to get and set the property's value.
  59. /// </summary>
  60. /// <remarks>Is <see langword="null"/> until <see cref="Initialize"/> is called.</remarks>
  61. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  62. internal static Dictionary<string, ConfigProperty>? _allConfigProperties;
  63. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  64. internal static readonly JsonSerializerOptions _serializerOptions = new ()
  65. {
  66. ReadCommentHandling = JsonCommentHandling.Skip,
  67. PropertyNameCaseInsensitive = true,
  68. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
  69. WriteIndented = true,
  70. Converters =
  71. {
  72. // We override the standard Rune converter to support specifying Glyphs in
  73. // a flexible way
  74. new RuneJsonConverter (),
  75. // Override Key to support "Ctrl+Q" format.
  76. new KeyJsonConverter ()
  77. },
  78. // Enables Key to be "Ctrl+Q" vs "Ctrl\u002BQ"
  79. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
  80. TypeInfoResolver = SourceGenerationContext.Default
  81. };
  82. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  83. internal static readonly SourceGenerationContext _serializerContext = new (_serializerOptions);
  84. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  85. internal static StringBuilder _jsonErrors = new ();
  86. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  87. private static readonly string _configFilename = "config.json";
  88. /// <summary>The backing property for <see cref="Settings"/>.</summary>
  89. /// <remarks>
  90. /// Is <see langword="null"/> until <see cref="Reset"/> is called. Gets set to a new instance by deserialization
  91. /// (see <see cref="Load"/>).
  92. /// </remarks>
  93. private static SettingsScope? _settings;
  94. /// <summary>Name of the running application. By default, this property is set to the application's assembly name.</summary>
  95. public static string AppName { get; set; } = Assembly.GetEntryAssembly ()?.FullName?.Split (',') [0]?.Trim ()!;
  96. /// <summary>Application-specific configuration settings scope.</summary>
  97. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  98. [JsonPropertyName ("AppSettings")]
  99. public static AppScope? AppSettings { get; set; }
  100. /// <summary>
  101. /// The set of glyphs used to draw checkboxes, lines, borders, etc...See also
  102. /// <seealso cref="Terminal.Gui.GlyphDefinitions"/>.
  103. /// </summary>
  104. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  105. [JsonPropertyName ("Glyphs")]
  106. public static GlyphDefinitions Glyphs { get; set; } = new ();
  107. /// <summary>
  108. /// Gets and sets the locations where <see cref="ConfigurationManager"/> will look for config files. The value is
  109. /// <see cref="ConfigLocations.All"/>.
  110. /// </summary>
  111. public static ConfigLocations Locations { get; set; } = ConfigLocations.All;
  112. /// <summary>
  113. /// The root object of Terminal.Gui configuration settings / JSON schema. Contains only properties with the
  114. /// <see cref="SettingsScope"/> attribute value.
  115. /// </summary>
  116. public static SettingsScope? Settings
  117. {
  118. [RequiresUnreferencedCode ("AOT")]
  119. [RequiresDynamicCode ("AOT")]
  120. get
  121. {
  122. if (_settings is null)
  123. {
  124. // If Settings is null, we need to initialize it.
  125. Reset ();
  126. }
  127. return _settings;
  128. }
  129. set => _settings = value!;
  130. }
  131. /// <summary>
  132. /// The root object of Terminal.Gui themes manager. Contains only properties with the <see cref="ThemeScope"/>
  133. /// attribute value.
  134. /// </summary>
  135. public static ThemeManager? Themes => ThemeManager.Instance;
  136. /// <summary>
  137. /// Gets or sets whether the <see cref="ConfigurationManager"/> should throw an exception if it encounters an
  138. /// error on deserialization. If <see langword="false"/> (the default), the error is logged and printed to the console
  139. /// when <see cref="Application.Shutdown"/> is called.
  140. /// </summary>
  141. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  142. public static bool? ThrowOnJsonErrors { get; set; } = false;
  143. /// <summary>Event fired when an updated configuration has been applied to the application.</summary>
  144. public static event EventHandler<ConfigurationManagerEventArgs>? Applied;
  145. /// <summary>Applies the configuration settings to the running <see cref="Application"/> instance.</summary>
  146. [RequiresUnreferencedCode ("AOT")]
  147. [RequiresDynamicCode ("AOT")]
  148. public static void Apply ()
  149. {
  150. var settings = false;
  151. var themes = false;
  152. var appSettings = false;
  153. try
  154. {
  155. if (string.IsNullOrEmpty (ThemeManager.SelectedTheme))
  156. {
  157. // First start. Apply settings first. This ensures if a config sets Theme to something other than "Default", it gets used
  158. settings = Settings?.Apply () ?? false;
  159. themes = !string.IsNullOrEmpty (ThemeManager.SelectedTheme)
  160. && (ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply () ?? false);
  161. }
  162. else
  163. {
  164. // Subsequently. Apply Themes first using whatever the SelectedTheme is
  165. themes = ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply () ?? false;
  166. settings = Settings?.Apply () ?? false;
  167. }
  168. appSettings = AppSettings?.Apply () ?? false;
  169. }
  170. catch (JsonException e)
  171. {
  172. if (ThrowOnJsonErrors ?? false)
  173. {
  174. throw;
  175. }
  176. else
  177. {
  178. AddJsonError ($"Error applying Configuration Change: {e.Message}");
  179. }
  180. }
  181. finally
  182. {
  183. if (settings || themes || appSettings)
  184. {
  185. OnApplied ();
  186. }
  187. }
  188. }
  189. /// <summary>Returns an empty Json document with just the $schema tag.</summary>
  190. /// <returns></returns>
  191. public static string GetEmptyJson ()
  192. {
  193. var emptyScope = new SettingsScope ();
  194. emptyScope.Clear ();
  195. return JsonSerializer.Serialize (emptyScope, typeof (SettingsScope), _serializerContext);
  196. }
  197. /// <summary>
  198. /// Gets or sets the in-memory config.json. See <see cref="ConfigLocations.Runtime"/>.
  199. /// </summary>
  200. public static string? RuntimeConfig { get; set; } = """{ }""";
  201. /// <summary>
  202. /// Loads all settings found in the configuration storage locations (<see cref="ConfigLocations"/>). Optionally, resets
  203. /// all settings attributed with
  204. /// <see cref="SerializableConfigurationProperty"/> to the defaults.
  205. /// </summary>
  206. /// <remarks>
  207. /// <para>
  208. /// Use <see cref="Apply"/> to cause the loaded settings to be applied to the running application.
  209. /// </para>
  210. /// </remarks>
  211. /// <param name="reset">
  212. /// If <see langword="true"/> the state of <see cref="ConfigurationManager"/> will be reset to the
  213. /// defaults (<see cref="ConfigLocations.Default"/>).
  214. /// </param>
  215. [RequiresUnreferencedCode ("AOT")]
  216. [RequiresDynamicCode ("AOT")]
  217. public static void Load (bool reset = false)
  218. {
  219. Debug.WriteLine ("ConfigurationManager.Load()");
  220. if (reset)
  221. {
  222. Reset ();
  223. }
  224. if (Locations.HasFlag (ConfigLocations.AppResources))
  225. {
  226. string? embeddedStylesResourceName = Assembly.GetEntryAssembly ()
  227. ?
  228. .GetManifestResourceNames ()
  229. .FirstOrDefault (x => x.EndsWith (_configFilename));
  230. if (string.IsNullOrEmpty (embeddedStylesResourceName))
  231. {
  232. embeddedStylesResourceName = _configFilename;
  233. }
  234. Settings?.UpdateFromResource (Assembly.GetEntryAssembly ()!, embeddedStylesResourceName!, ConfigLocations.AppResources);
  235. }
  236. if (Locations.HasFlag (ConfigLocations.Runtime) && !string.IsNullOrEmpty (RuntimeConfig))
  237. {
  238. Settings?.Update (RuntimeConfig, "ConfigurationManager.RuntimeConfig", ConfigLocations.Runtime);
  239. }
  240. if (Locations.HasFlag (ConfigLocations.GlobalCurrent))
  241. {
  242. Settings?.Update ($"./.tui/{_configFilename}", ConfigLocations.GlobalCurrent);
  243. }
  244. if (Locations.HasFlag (ConfigLocations.GlobalHome))
  245. {
  246. Settings?.Update ($"~/.tui/{_configFilename}", ConfigLocations.GlobalHome);
  247. }
  248. if (Locations.HasFlag (ConfigLocations.AppCurrent))
  249. {
  250. Settings?.Update ($"./.tui/{AppName}.{_configFilename}", ConfigLocations.AppCurrent);
  251. }
  252. if (Locations.HasFlag (ConfigLocations.AppHome))
  253. {
  254. Settings?.Update ($"~/.tui/{AppName}.{_configFilename}", ConfigLocations.AppHome);
  255. }
  256. ThemeManager.SelectedTheme = Settings!["Theme"].PropertyValue as string ?? "Default";
  257. }
  258. /// <summary>
  259. /// Called when an updated configuration has been applied to the application. Fires the <see cref="Applied"/>
  260. /// event.
  261. /// </summary>
  262. public static void OnApplied ()
  263. {
  264. Debug.WriteLine ("ConfigurationManager.OnApplied()");
  265. Applied?.Invoke (null, new ());
  266. // TODO: Refactor ConfigurationManager to not use an event handler for this.
  267. // Instead, have it call a method on any class appropriately attributed
  268. // to update the cached values. See Issue #2871
  269. }
  270. /// <summary>
  271. /// Called when the configuration has been updated from a configuration file or reset. Invokes the
  272. /// <see cref="Updated"/>
  273. /// event.
  274. /// </summary>
  275. public static void OnUpdated ()
  276. {
  277. Debug.WriteLine (@"ConfigurationManager.OnUpdated()");
  278. Updated?.Invoke (null, new ());
  279. }
  280. /// <summary>Prints any Json deserialization errors that occurred during deserialization to the console.</summary>
  281. public static void PrintJsonErrors ()
  282. {
  283. if (_jsonErrors.Length > 0)
  284. {
  285. Console.WriteLine (
  286. @"Terminal.Gui ConfigurationManager encountered the following errors while deserializing configuration files:"
  287. );
  288. Console.WriteLine (_jsonErrors.ToString ());
  289. }
  290. }
  291. /// <summary>
  292. /// Resets the state of <see cref="ConfigurationManager"/>. Should be called whenever a new app session (e.g. in
  293. /// <see cref="Application.Init"/> starts. Called by <see cref="Load"/> if the <c>reset</c> parameter is
  294. /// <see langword="true"/>.
  295. /// </summary>
  296. /// <remarks></remarks>
  297. [RequiresUnreferencedCode ("AOT")]
  298. [RequiresDynamicCode ("AOT")]
  299. public static void Reset ()
  300. {
  301. Debug.WriteLine (@"ConfigurationManager.Reset()");
  302. if (_allConfigProperties is null)
  303. {
  304. Initialize ();
  305. }
  306. ClearJsonErrors ();
  307. Settings = new ();
  308. ThemeManager.Reset ();
  309. AppSettings = new ();
  310. // To enable some unit tests, we only load from resources if the flag is set
  311. if (Locations.HasFlag (ConfigLocations.Default))
  312. {
  313. Settings.UpdateFromResource (
  314. typeof (ConfigurationManager).Assembly,
  315. $"Terminal.Gui.Resources.{_configFilename}",
  316. ConfigLocations.Default
  317. );
  318. }
  319. OnUpdated ();
  320. Apply ();
  321. ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply ();
  322. AppSettings?.Apply ();
  323. }
  324. /// <summary>Event fired when the configuration has been updated from a configuration source or reset.</summary>
  325. public static event EventHandler<ConfigurationManagerEventArgs>? Updated;
  326. internal static void AddJsonError (string error)
  327. {
  328. Debug.WriteLine ($"ConfigurationManager: {error}");
  329. _jsonErrors.AppendLine (error);
  330. }
  331. /// <summary>
  332. /// System.Text.Json does not support copying a deserialized object to an existing instance. To work around this,
  333. /// we implement a 'deep, member-wise copy' method.
  334. /// </summary>
  335. /// <remarks>TOOD: When System.Text.Json implements `PopulateObject` revisit https://github.com/dotnet/corefx/issues/37627</remarks>
  336. /// <param name="source"></param>
  337. /// <param name="destination"></param>
  338. /// <returns><paramref name="destination"/> updated from <paramref name="source"/></returns>
  339. internal static object? DeepMemberWiseCopy (object? source, object? destination)
  340. {
  341. ArgumentNullException.ThrowIfNull (destination);
  342. if (source is null)
  343. {
  344. return null!;
  345. }
  346. if (source.GetType () == typeof (SettingsScope))
  347. {
  348. return ((SettingsScope)destination).Update ((SettingsScope)source);
  349. }
  350. if (source.GetType () == typeof (ThemeScope))
  351. {
  352. return ((ThemeScope)destination).Update ((ThemeScope)source);
  353. }
  354. if (source.GetType () == typeof (AppScope))
  355. {
  356. return ((AppScope)destination).Update ((AppScope)source);
  357. }
  358. // If value type, just use copy constructor.
  359. if (source.GetType ().IsValueType || source is string)
  360. {
  361. return source;
  362. }
  363. // HACK: Key is a class, but we want to treat it as a value type so just _keyCode gets copied.
  364. if (source.GetType () == typeof (Key))
  365. {
  366. return source;
  367. }
  368. // Dictionary
  369. if (source.GetType ().IsGenericType
  370. && source.GetType ().GetGenericTypeDefinition ().IsAssignableFrom (typeof (Dictionary<,>)))
  371. {
  372. foreach (object? srcKey in ((IDictionary)source).Keys)
  373. {
  374. if (((IDictionary)destination).Contains (srcKey))
  375. {
  376. ((IDictionary)destination) [srcKey] =
  377. DeepMemberWiseCopy (((IDictionary)source) [srcKey], ((IDictionary)destination) [srcKey]);
  378. }
  379. else
  380. {
  381. ((IDictionary)destination).Add (srcKey, ((IDictionary)source) [srcKey]);
  382. }
  383. }
  384. return destination;
  385. }
  386. // ALl other object types
  387. List<PropertyInfo>? sourceProps = source?.GetType ().GetProperties ().Where (x => x.CanRead).ToList ();
  388. List<PropertyInfo>? destProps = destination?.GetType ().GetProperties ().Where (x => x.CanWrite).ToList ()!;
  389. foreach ((PropertyInfo? sourceProp, PropertyInfo? destProp) in
  390. from sourceProp in sourceProps
  391. where destProps.Any (x => x.Name == sourceProp.Name)
  392. let destProp = destProps.First (x => x.Name == sourceProp.Name)
  393. where destProp.CanWrite
  394. select (sourceProp, destProp))
  395. {
  396. object? sourceVal = sourceProp.GetValue (source);
  397. object? destVal = destProp.GetValue (destination);
  398. if (sourceVal is { })
  399. {
  400. try
  401. {
  402. if (destVal is { })
  403. {
  404. // Recurse
  405. destProp.SetValue (destination, DeepMemberWiseCopy (sourceVal, destVal));
  406. }
  407. else
  408. {
  409. destProp.SetValue (destination, sourceVal);
  410. }
  411. }
  412. catch (ArgumentException e)
  413. {
  414. throw new JsonException ($"Error Applying Configuration Change: {e.Message}", e);
  415. }
  416. }
  417. }
  418. return destination;
  419. }
  420. /// <summary>
  421. /// Retrieves the hard coded default settings (static properites) from the Terminal.Gui library implementation. Used in
  422. /// development of
  423. /// the library to generate the default configuration file.
  424. /// </summary>
  425. /// <remarks>
  426. /// <para>
  427. /// This method is only really useful when using ConfigurationManagerTests to generate the JSON doc that is
  428. /// embedded into Terminal.Gui (during development).
  429. /// </para>
  430. /// <para>
  431. /// WARNING: The <c>Terminal.Gui.Resources.config.json</c> resource has setting definitions (Themes) that are NOT
  432. /// generated by this function. If you use this function to regenerate <c>Terminal.Gui.Resources.config.json</c>,
  433. /// make sure you copy the Theme definitions from the existing <c>Terminal.Gui.Resources.config.json</c> file.
  434. /// </para>
  435. /// </remarks>
  436. [RequiresUnreferencedCode ("AOT")]
  437. [RequiresDynamicCode ("AOT")]
  438. internal static void GetHardCodedDefaults ()
  439. {
  440. if (_allConfigProperties is null)
  441. {
  442. throw new InvalidOperationException ("Initialize must be called first.");
  443. }
  444. Settings = new ();
  445. ThemeManager.GetHardCodedDefaults ();
  446. AppSettings?.RetrieveValues ();
  447. foreach (KeyValuePair<string, ConfigProperty> p in Settings!.Where (cp => cp.Value.PropertyInfo is { }))
  448. {
  449. Settings! [p.Key].PropertyValue = p.Value.PropertyInfo?.GetValue (null);
  450. }
  451. }
  452. /// <summary>
  453. /// Initializes the internal state of ConfigurationManager. Nominally called once as part of application startup
  454. /// to initialize global state. Also called from some Unit Tests to ensure correctness (e.g. Reset()).
  455. /// </summary>
  456. [RequiresUnreferencedCode ("AOT")]
  457. internal static void Initialize ()
  458. {
  459. _allConfigProperties = new ();
  460. _settings = null;
  461. Dictionary<string, Type> classesWithConfigProps = new (StringComparer.InvariantCultureIgnoreCase);
  462. // Get Terminal.Gui.dll classes
  463. IEnumerable<Type> types = from assembly in AppDomain.CurrentDomain.GetAssemblies ()
  464. from type in assembly.GetTypes ()
  465. where type.GetProperties ()
  466. .Any (
  467. prop => prop.GetCustomAttribute (
  468. typeof (SerializableConfigurationProperty)
  469. )
  470. != null
  471. )
  472. select type;
  473. foreach (Type? classWithConfig in types)
  474. {
  475. classesWithConfigProps.Add (classWithConfig.Name, classWithConfig);
  476. }
  477. //Debug.WriteLine ($"ConfigManager.getConfigProperties found {classesWithConfigProps.Count} classes:");
  478. classesWithConfigProps.ToList ().ForEach (x => Debug.WriteLine ($" Class: {x.Key}"));
  479. foreach (PropertyInfo? p in from c in classesWithConfigProps
  480. let props = c.Value
  481. .GetProperties (
  482. BindingFlags.Instance
  483. |
  484. BindingFlags.Static
  485. |
  486. BindingFlags.NonPublic
  487. |
  488. BindingFlags.Public
  489. )
  490. .Where (
  491. prop =>
  492. prop.GetCustomAttribute (
  493. typeof (SerializableConfigurationProperty)
  494. ) is
  495. SerializableConfigurationProperty
  496. )
  497. let enumerable = props
  498. from p in enumerable
  499. select p)
  500. {
  501. if (p.GetCustomAttribute (typeof (SerializableConfigurationProperty)) is SerializableConfigurationProperty
  502. scp)
  503. {
  504. if (p.GetGetMethod (true)!.IsStatic)
  505. {
  506. // If the class name is omitted, JsonPropertyName is allowed.
  507. _allConfigProperties!.Add (
  508. scp.OmitClassName
  509. ? ConfigProperty.GetJsonPropertyName (p)
  510. : $"{p.DeclaringType?.Name}.{p.Name}",
  511. new () { PropertyInfo = p, PropertyValue = null }
  512. );
  513. }
  514. else
  515. {
  516. throw new (
  517. $"Property {p.Name} in class {p.DeclaringType?.Name} is not static. All SerializableConfigurationProperty properties must be static."
  518. );
  519. }
  520. }
  521. }
  522. _allConfigProperties = _allConfigProperties!.OrderBy (x => x.Key)
  523. .ToDictionary (
  524. x => x.Key,
  525. x => x.Value,
  526. StringComparer.InvariantCultureIgnoreCase
  527. );
  528. //Debug.WriteLine ($"ConfigManager.Initialize found {_allConfigProperties.Count} properties:");
  529. //_allConfigProperties.ToList ().ForEach (x => Debug.WriteLine ($" Property: {x.Key}"));
  530. AppSettings = new ();
  531. }
  532. /// <summary>Creates a JSON document with the configuration specified.</summary>
  533. /// <returns></returns>
  534. [RequiresUnreferencedCode ("AOT")]
  535. [RequiresDynamicCode ("AOT")]
  536. internal static string ToJson ()
  537. {
  538. //Debug.WriteLine ("ConfigurationManager.ToJson()");
  539. return JsonSerializer.Serialize (Settings!, typeof (SettingsScope), _serializerContext);
  540. }
  541. [RequiresUnreferencedCode ("AOT")]
  542. [RequiresDynamicCode ("AOT")]
  543. internal static Stream ToStream ()
  544. {
  545. string json = JsonSerializer.Serialize (Settings!, typeof (SettingsScope), _serializerContext);
  546. // turn it into a stream
  547. var stream = new MemoryStream ();
  548. var writer = new StreamWriter (stream);
  549. writer.Write (json);
  550. writer.Flush ();
  551. stream.Position = 0;
  552. return stream;
  553. }
  554. private static void ClearJsonErrors () { _jsonErrors.Clear (); }
  555. }