/ src / modules / cmdpal / ext / Microsoft.CmdPal.Ext.WindowsSettings / Helpers / JsonSettingsListHelper.cs
JsonSettingsListHelper.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.IO; 7 using System.Reflection; 8 using System.Text.Json; 9 using ManagedCommon; 10 11 namespace Microsoft.CmdPal.Ext.WindowsSettings.Helpers; 12 13 /// <summary> 14 /// Helper class to easier work with the JSON file that contains all Windows settings 15 /// </summary> 16 internal static class JsonSettingsListHelper 17 { 18 /// <summary> 19 /// The name of the file that contains all settings for the query 20 /// </summary> 21 private const string _settingsFile = "WindowsSettings.json"; 22 23 private const string _extTypeNamespace = "Microsoft.CmdPal.Ext.WindowsSettings"; 24 25 private static readonly JsonSerializerOptions _serializerOptions = new() 26 { 27 }; 28 29 /// <summary> 30 /// Read all possible Windows settings. 31 /// </summary> 32 /// <returns>A list with all possible windows settings.</returns> 33 internal static Classes.WindowsSettings ReadAllPossibleSettings() 34 { 35 var assembly = Assembly.GetExecutingAssembly(); 36 37 #pragma warning disable CS8632 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. 38 Classes.WindowsSettings? settings = null; 39 #pragma warning restore CS8632 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. 40 41 try 42 { 43 var resourceName = $"{_extTypeNamespace}.{_settingsFile}"; 44 using var stream = assembly.GetManifestResourceStream(resourceName); 45 if (stream is null) 46 { 47 throw new ArgumentNullException(nameof(stream), "stream is null"); 48 } 49 50 var options = _serializerOptions; 51 52 // Why we need it? I don't see any enum usage in WindowsSettings 53 // options.Converters.Add(new JsonStringEnumConverter()); 54 using var reader = new StreamReader(stream); 55 var text = reader.ReadToEnd(); 56 57 settings = JsonSerializer.Deserialize(text, WindowsSettingsJsonSerializationContext.Default.WindowsSettings); 58 } 59 #pragma warning disable CS0168 60 catch (Exception exception) 61 { 62 // TODO GH #108 Logging is something we have to take care of 63 // Log.Exception("Error loading settings JSON file", exception, typeof(JsonSettingsListHelper)); 64 Logger.LogError($"Error loading settings JSON file: {exception.Message}"); 65 } 66 #pragma warning restore CS0168 67 return settings ?? new Classes.WindowsSettings(); 68 } 69 }