-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathParamService.cs
More file actions
93 lines (85 loc) · 2.99 KB
/
ParamService.cs
File metadata and controls
93 lines (85 loc) · 2.99 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
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WSLAttachSwitch
{
//This is required due to AOT compilation and assembly trimming:
[JsonSerializable(typeof(Params))]
[JsonSourceGenerationOptions(WriteIndented = true)]
public partial class JsonContext : JsonSerializerContext
{
}
public record Params(string Network, string? MacAddress, int? Vlan)
{
public override string ToString()
{
return $"Network: {Network}, MAC: {MacAddress}, VLAN: {Vlan}";
}
public bool AreValid()
{
return !string.IsNullOrEmpty(Network);
}
}
internal class ParamService
{
private static readonly string AppFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"WSLAttachSwitch");
private static readonly string ParamsFile = Path.Combine(AppFolder, "params.json");
public static bool Save(Params parameters)
{
try
{
Directory.CreateDirectory(AppFolder);
string json = JsonSerializer.Serialize(parameters, JsonContext.Default.Params);
File.WriteAllText(ParamsFile, json);
return true;
}
catch
{
return false;
}
}
public static bool TryLoad(out Params parameters)
{
try
{
if (File.Exists(ParamsFile))
{
var json = File.ReadAllText(ParamsFile);
parameters = JsonSerializer.Deserialize<Params>(json, JsonContext.Default.Params) ?? new Params(string.Empty, null, null);
Console.WriteLine($"Loaded parameters: {parameters}");
return true;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error while loading saved parameters: {ex.Message}");
}
parameters = new Params(string.Empty, null, null);
return false;
}
public static bool GetOrLoadParams(string? network, string? macAddress, int? vlanId, out Params paramsToBeUsed)
{
Params passedParams = new(network ?? string.Empty, macAddress, vlanId);
if (passedParams.AreValid())
{
paramsToBeUsed = passedParams;
return true;
}
else
{
if (TryLoad(out Params? savedParams) && savedParams.AreValid())
{
paramsToBeUsed = savedParams;
return true;
}
else
{
Console.Error.WriteLine("No network specified and no saved parameters found. Use --network option to specify a network.");
paramsToBeUsed = passedParams;
return false;
}
}
}
}
}