-
Notifications
You must be signed in to change notification settings - Fork 804
Expand file tree
/
Copy pathSettingsManager.cs
More file actions
489 lines (391 loc) · 15.9 KB
/
SettingsManager.cs
File metadata and controls
489 lines (391 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
using log4net;
using NETworkManager.Models;
using NETworkManager.Models.Network;
using NETworkManager.Utilities;
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Serialization;
namespace NETworkManager.Settings;
public static class SettingsManager
{
#region Variables
/// <summary>
/// Logger for logging.
/// </summary>
private static readonly ILog Log = LogManager.GetLogger(typeof(SettingsManager));
/// <summary>
/// Settings directory name.
/// </summary>
private static string SettingsFolderName => "Settings";
/// <summary>
/// Settings backups directory name.
/// </summary>
private static string BackupFolderName => "Backups";
/// <summary>
/// Settings file name.
/// </summary>
private static string SettingsFileName => "Settings";
/// <summary>
/// Settings file extension.
/// </summary>
private static string SettingsFileExtension => ".json";
/// <summary>
/// Legacy XML settings file extension.
/// </summary>
[Obsolete("Legacy XML settings are no longer used, but the extension is kept for migration purposes.")]
private static string LegacySettingsFileExtension => ".xml";
/// <summary>
/// Settings that are currently loaded.
/// </summary>
public static SettingsInfo Current { get; private set; }
/// <summary>
/// Indicates if the HotKeys have changed. May need to be reworked if we add more HotKeys.
/// </summary>
public static bool HotKeysChanged { get; set; }
/// <summary>
/// JSON serializer options for consistent serialization/deserialization.
/// </summary>
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
Converters = { new JsonStringEnumConverter() }
};
#endregion
#region Settings location, default paths and file names
/// <summary>
/// Method to get the path of the settings folder.
/// </summary>
/// <returns>Path to the settings folder.</returns>
public static string GetSettingsFolderLocation()
{
return ConfigurationManager.Current.IsPortable
? Path.Combine(AssemblyManager.Current.Location, SettingsFolderName)
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
AssemblyManager.Current.Name, SettingsFolderName);
}
/// <summary>
/// Method to get the path of the settings backup folder.
/// </summary>
/// <returns>Path to the settings backup folder.</returns>
public static string GetSettingsBackupFolderLocation()
{
return Path.Combine(GetSettingsFolderLocation(), BackupFolderName);
}
/// <summary>
/// Method to get the settings file name.
/// </summary>
/// <returns>Settings file name.</returns>
public static string GetSettingsFileName()
{
return $"{SettingsFileName}{SettingsFileExtension}";
}
/// <summary>
/// Method to get the legacy settings file name.
/// </summary>
/// <returns>Legacy settings file name.</returns>
[Obsolete("Legacy XML settings are no longer used, but the method is kept for migration purposes.")]
public static string GetLegacySettingsFileName()
{
return $"{SettingsFileName}{LegacySettingsFileExtension}";
}
/// <summary>
/// Method to get the settings file path.
/// </summary>
/// <returns>Settings file path.</returns>
public static string GetSettingsFilePath()
{
return Path.Combine(GetSettingsFolderLocation(), GetSettingsFileName());
}
/// <summary>
/// Method to get the legacy XML settings file path.
/// </summary>
/// <returns>Legacy XML settings file path.</returns>
[Obsolete("Legacy XML settings are no longer used, but the method is kept for migration purposes.")]
private static string GetLegacySettingsFilePath()
{
return Path.Combine(GetSettingsFolderLocation(), GetLegacySettingsFileName());
}
#endregion
#region Initialize, load and save
/// <summary>
/// Initialize new settings (<see cref="SettingsInfo" />) and save them (to a file).
/// </summary>
public static void Initialize()
{
Current = new SettingsInfo
{
Version = AssemblyManager.Current.Version.ToString()
};
Save();
}
/// <summary>
/// Method to load the settings (from a file).
/// </summary>
public static void Load()
{
var filePath = GetSettingsFilePath();
var legacyFilePath = GetLegacySettingsFilePath();
// Check if JSON file exists
if (File.Exists(filePath))
{
Current = DeserializeFromFile(filePath);
Current.SettingsChanged = false;
return;
}
// Check if legacy XML file exists and migrate it
if (File.Exists(legacyFilePath))
{
Log.Info("Legacy XML settings file found. Migrating to JSON format...");
Current = DeserializeFromXmlFile(legacyFilePath);
Current.SettingsChanged = false;
// Save in new JSON format
Save();
// Create a backup of the legacy XML file and delete the original
Directory.CreateDirectory(GetSettingsBackupFolderLocation());
var backupFilePath = Path.Combine(GetSettingsBackupFolderLocation(),
$"{TimestampHelper.GetTimestamp()}_{GetLegacySettingsFileName()}");
File.Copy(legacyFilePath, backupFilePath, true);
File.Delete(legacyFilePath);
Log.Info($"Legacy XML settings file backed up to: {backupFilePath}");
Log.Info("Settings migration from XML to JSON completed successfully.");
return;
}
// Initialize the default settings if there is no settings file.
Initialize();
}
/// <summary>
/// Method to deserialize the settings from a JSON file.
/// </summary>
/// <param name="filePath">Path to the settings file.</param>
/// <returns>Settings as <see cref="SettingsInfo" />.</returns>
private static SettingsInfo DeserializeFromFile(string filePath)
{
var jsonString = File.ReadAllText(filePath);
var settingsInfo = JsonSerializer.Deserialize<SettingsInfo>(jsonString, JsonOptions);
return settingsInfo;
}
/// <summary>
/// Method to deserialize the settings from a legacy XML file.
/// </summary>
/// <param name="filePath">Path to the XML settings file.</param>
/// <returns>Settings as <see cref="SettingsInfo" />.</returns>
[Obsolete("Legacy XML settings are no longer used, but the method is kept for migration purposes.")]
private static SettingsInfo DeserializeFromXmlFile(string filePath)
{
var xmlSerializer = new XmlSerializer(typeof(SettingsInfo));
using var fileStream = new FileStream(filePath, FileMode.Open);
var settingsInfo = xmlSerializer.Deserialize(fileStream) as SettingsInfo;
return settingsInfo;
}
/// <summary>
/// Method to save the currently loaded settings (to a file).
/// </summary>
public static void Save()
{
// Create the directory if it does not exist
Directory.CreateDirectory(GetSettingsFolderLocation());
// Serialize the settings to a file
SerializeToFile(GetSettingsFilePath());
// Set the setting changed to false after saving them as file...
Current.SettingsChanged = false;
}
/// <summary>
/// Method to serialize the settings to a JSON file.
/// </summary>
/// <param name="filePath">Path to the settings file.</param>
private static void SerializeToFile(string filePath)
{
var jsonString = JsonSerializer.Serialize(Current, JsonOptions);
File.WriteAllText(filePath, jsonString);
}
#endregion
#region Backup
/*
private static void Backup()
{
Log.Info("Creating settings backup...");
// Create the backup directory if it does not exist
Directory.CreateDirectory(GetSettingsBackupFolderLocation());
}
*/
#endregion
#region Upgrade
/// <summary>
/// Method to upgrade the settings.
/// </summary>
/// <param name="fromVersion">Previous used version.</param>
/// <param name="toVersion">Target version.</param>
public static void Upgrade(Version fromVersion, Version toVersion)
{
Log.Info($"Start settings upgrade from {fromVersion} to {toVersion}...");
// 2023.3.7.0
if (fromVersion < new Version(2023, 3, 7, 0))
UpgradeTo_2023_3_7_0();
// 2023.4.26.0
if (fromVersion < new Version(2023, 4, 26, 0))
UpgradeTo_2023_4_26_0();
// 2023.6.27.0
if (fromVersion < new Version(2023, 6, 27, 0))
UpgradeTo_2023_6_27_0();
// 2023.11.28.0
if (fromVersion < new Version(2023, 11, 28, 0))
UpgradeTo_2023_11_28_0();
// 2024.11.11.0
if (fromVersion < new Version(2024, 11, 11, 0))
UpgradeTo_2024_11_11_0();
// 2025.8.11.0
if (fromVersion < new Version(2025, 8, 11, 0))
UpgradeTo_2025_8_11_0();
// Latest
if (fromVersion < toVersion)
UpgradeToLatest(toVersion);
// Update to the latest version and save
Current.UpgradeDialog_Show = true;
Current.Version = toVersion.ToString();
Save();
Log.Info("Settings upgrade finished!");
}
/// <summary>
/// Method to apply changes for version 2023.3.7.0.
/// </summary>
private static void UpgradeTo_2023_3_7_0()
{
Log.Info("Apply update to 2023.3.7.0...");
// Add NTP Lookup application
Log.Info("Add new app \"SNTPLookup\"...");
Current.General_ApplicationList.Add(ApplicationManager.GetDefaultList()
.First(x => x.Name == ApplicationName.SNTPLookup));
Current.SNTPLookup_SNTPServers =
[.. SNTPServer.GetDefaultList()];
// Add IP Scanner custom commands
foreach (var customCommand in from customCommand in IPScannerCustomCommand.GetDefaultList()
let customCommandFound =
Current.IPScanner_CustomCommands.FirstOrDefault(x => x.Name == customCommand.Name)
where customCommandFound == null
select customCommand)
{
Log.Info($"Add \"{customCommand.Name}\" to \"IPScanner_CustomCommands\"...");
Current.IPScanner_CustomCommands.Add(customCommand);
}
// Add or update Port Scanner port profiles
foreach (var portProfile in PortProfile.GetDefaultList())
{
var portProfileFound = Current.PortScanner_PortProfiles.FirstOrDefault(x => x.Name == portProfile.Name);
if (portProfileFound == null)
{
Log.Info($"Add \"{portProfile.Name}\" to \"PortScanner_PortProfiles\"...");
Current.PortScanner_PortProfiles.Add(portProfile);
}
else if (!portProfile.Ports.Equals(portProfileFound.Ports))
{
Log.Info($"Update \"{portProfile.Name}\" in \"PortScanner_PortProfiles\"...");
Current.PortScanner_PortProfiles.Remove(portProfileFound);
Current.PortScanner_PortProfiles.Add(portProfile);
}
}
// Add new DNS lookup profiles
Log.Info("Init \"DNSLookup_DNSServers_v2\" with default DNS servers...");
Current.DNSLookup_DNSServers =
[.. DNSServer.GetDefaultList()];
}
/// <summary>
/// Method to apply changes for version 2023.4.26.0.
/// </summary>
private static void UpgradeTo_2023_4_26_0()
{
Log.Info("Apply update to 2023.4.26.0...");
// Add SNMP OID profiles
Log.Info("Add SNMP OID profiles...");
Current.SNMP_OidProfiles = [.. SNMPOIDProfile.GetDefaultList()];
}
/// <summary>
/// Method to apply changes for version 2023.6.27.0.
/// </summary>
private static void UpgradeTo_2023_6_27_0()
{
Log.Info("Apply update to 2023.6.27.0...");
// Update Wake on LAN settings
Log.Info($"Update \"WakeOnLAN_Port\" to {GlobalStaticConfiguration.WakeOnLAN_Port}");
Current.WakeOnLAN_Port = GlobalStaticConfiguration.WakeOnLAN_Port;
}
/// <summary>
/// Method to apply changes for version 2023.11.28.0.
/// </summary>
private static void UpgradeTo_2023_11_28_0()
{
Log.Info("Apply upgrade to 2023.11.28.0...");
// First run is required due to the new settings
Log.Info("Set \"FirstRun\" to true...");
Current.WelcomeDialog_Show = true;
// Add IP geolocation application
Log.Info("Add new app \"IP Geolocation\"...");
Current.General_ApplicationList.Add(ApplicationManager.GetDefaultList()
.First(x => x.Name == ApplicationName.IPGeolocation));
// Add DNS lookup profiles after refactoring
Log.Info("Init \"DNSLookup_DNSServers\" with default DNS servers...");
Current.DNSLookup_DNSServers =
[.. DNSServer.GetDefaultList()];
}
/// <summary>
/// Method to apply changes for version 2024.11.11.0.
/// </summary>
private static void UpgradeTo_2024_11_11_0()
{
Log.Info("Apply upgrade to 2024.11.11.0...");
Log.Info("Reset ApplicationList to default...");
Current.General_ApplicationList =
[.. ApplicationManager.GetDefaultList()];
}
/// <summary>
/// Method to apply changes for version 2025.8.11.0.
/// </summary>
private static void UpgradeTo_2025_8_11_0()
{
Log.Info("Apply upgrade to 2025.8.11.0...");
// Add Hosts editor application
Log.Info("Add new app \"Hosts File Editor\"...");
Current.General_ApplicationList.Insert(
ApplicationManager.GetDefaultList().ToList().FindIndex(x => x.Name == ApplicationName.HostsFileEditor),
ApplicationManager.GetDefaultList().First(x => x.Name == ApplicationName.HostsFileEditor));
}
/// <summary>
/// Method to apply changes for the latest version.
/// </summary>
/// <param name="version">Latest version.</param>
private static void UpgradeToLatest(Version version)
{
Log.Info($"Apply upgrade to {version}...");
// DNS Lookup
Log.Info("Migrate DNS Lookup settings to new structure...");
Current.DNSLookup_SelectedDNSServer_v2 = Current.DNSLookup_SelectedDNSServer?.Name;
Log.Info($"Selected DNS server set to \"{Current.DNSLookup_SelectedDNSServer_v2}\"");
// AWS Session Manager
Log.Info("Removing deprecated app \"AWS Session Manager\", if it exists...");
var appToRemove = Current.General_ApplicationList
.FirstOrDefault(x => x.Name == ApplicationName.AWSSessionManager);
if (appToRemove != null)
{
if (appToRemove.IsDefault)
{
Log.Info("\"AWS Session Manager\" is set as the default app. Setting the new default app to the first visible app...");
var newDefaultApp = Current.General_ApplicationList.FirstOrDefault(x => x.IsVisible);
if (newDefaultApp != null)
{
Log.Info($"Set \"{newDefaultApp.Name}\" as the new default app");
newDefaultApp.IsDefault = true;
}
else
{
Log.Error("No visible app found to set as the new default app.");
}
}
Current.General_ApplicationList.Remove(appToRemove);
}
}
#endregion
}