ConfigurationManager.cs 26 KB

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