Winify – Diff between revs 75 and 77

Subversion Repositories:
Rev:
Only display areas with differencesIgnore whitespace
Rev 75 Rev 77
1 using System; 1 using System;
2 using System.Collections.Concurrent; 2 using System.Collections.Concurrent;
3 using System.ComponentModel; 3 using System.ComponentModel;
4 using System.Drawing; 4 using System.Drawing;
5 using System.IO; 5 using System.IO;
6 using System.Net; 6 using System.Net;
7 using System.Reflection; 7 using System.Reflection;
8 using System.Text; 8 using System.Text;
9 using System.Threading; 9 using System.Threading;
10 using System.Threading.Tasks; 10 using System.Threading.Tasks;
11 using System.Windows.Forms; 11 using System.Windows.Forms;
-   12 using Microsoft.Win32;
12 using NetSparkleUpdater; 13 using NetSparkleUpdater;
13 using NetSparkleUpdater.Enums; 14 using NetSparkleUpdater.Enums;
14 using NetSparkleUpdater.SignatureVerifiers; 15 using NetSparkleUpdater.SignatureVerifiers;
15 using NetSparkleUpdater.UI.WinForms; 16 using NetSparkleUpdater.UI.WinForms;
16 using Serilog; 17 using Serilog;
17 using Servers; 18 using Servers;
18 using Toasts; 19 using Toasts;
19 using Winify.Gotify; 20 using Winify.Gotify;
20 using Winify.Settings; 21 using Winify.Settings;
21 using Winify.Utilities; 22 using Winify.Utilities;
22 using Winify.Utilities.Serialization; 23 using Winify.Utilities.Serialization;
23 using ScheduledContinuation = Toasts.ScheduledContinuation; 24 using ScheduledContinuation = Toasts.ScheduledContinuation;
24   25  
25 namespace Winify 26 namespace Winify
26 { 27 {
27 public partial class MainForm : Form 28 public partial class MainForm : Form
28 { 29 {
29 #region Public Enums, Properties and Fields 30 #region Public Enums, Properties and Fields
30   31  
31 public Configuration.Configuration Configuration { get; set; } 32 public Configuration.Configuration Configuration { get; set; }
32   33  
33 public ScheduledContinuation ChangedConfigurationContinuation { get; set; } 34 public ScheduledContinuation ChangedConfigurationContinuation { get; set; }
34   35  
35 public bool MemorySinkEnabled { get; set; } 36 public bool MemorySinkEnabled { get; set; }
36   37  
37 #endregion 38 #endregion
38   39  
39 #region Private Delegates, Events, Enums, Properties, Indexers and Fields 40 #region Private Delegates, Events, Enums, Properties, Indexers and Fields
40   41  
41 private AboutForm _aboutForm; 42 private AboutForm _aboutForm;
42   43  
43 private ConcurrentBag<GotifyConnection> _gotifyConnections; 44 private ConcurrentBag<GotifyConnection> _gotifyConnections;
44   45  
45 private SettingsForm _settingsForm; 46 private SettingsForm _settingsForm;
46   47  
47 private readonly SparkleUpdater _sparkle; 48 private readonly SparkleUpdater _sparkle;
48   49  
49 private readonly CancellationTokenSource _cancellationTokenSource; 50 private readonly CancellationTokenSource _cancellationTokenSource;
50   51  
51 private readonly CancellationToken _cancellationToken; 52 private readonly CancellationToken _cancellationToken;
52   53  
53 private LogViewForm _logViewForm; 54 private LogViewForm _logViewForm;
54   55  
55 private readonly LogMemorySink _memorySink; 56 private readonly LogMemorySink _memorySink;
56   57  
57 private readonly Toasts.Toasts _toasts; 58 private readonly Toasts.Toasts _toasts;
58   59  
59 #endregion 60 #endregion
60   61  
61 #region Constructors, Destructors and Finalizers 62 #region Constructors, Destructors and Finalizers
62   63  
63 public MainForm() 64 public MainForm()
64 { 65 {
65 InitializeComponent(); 66 InitializeComponent();
-   67  
-   68 SystemEvents.PowerModeChanged += OnPowerModeChanged;
66   69  
67 _cancellationTokenSource = new CancellationTokenSource(); 70 _cancellationTokenSource = new CancellationTokenSource();
68 _cancellationToken = _cancellationTokenSource.Token; 71 _cancellationToken = _cancellationTokenSource.Token;
69   72  
70 ChangedConfigurationContinuation = new ScheduledContinuation(); 73 ChangedConfigurationContinuation = new ScheduledContinuation();
71   74  
72 _toasts = new Toasts.Toasts(_cancellationToken); 75 _toasts = new Toasts.Toasts(_cancellationToken);
73 } 76 }
74   77  
75 public MainForm(Mutex mutex) : this() 78 public MainForm(Mutex mutex) : this()
76 { 79 {
77 _memorySink = new LogMemorySink(); 80 _memorySink = new LogMemorySink();
78 Log.Logger = new LoggerConfiguration() 81 Log.Logger = new LoggerConfiguration()
79 .MinimumLevel.Debug() 82 .MinimumLevel.Debug()
80 .WriteTo.Conditional(condition => MemorySinkEnabled, configureSink => configureSink.Sink(_memorySink)) 83 .WriteTo.Conditional(condition => MemorySinkEnabled, configureSink => configureSink.Sink(_memorySink))
81 .WriteTo.File(Path.Combine(Constants.UserApplicationDirectory, "Logs", $"{Constants.AssemblyName}.log"), 84 .WriteTo.File(Path.Combine(Constants.UserApplicationDirectory, "Logs", $"{Constants.AssemblyName}.log"),
82 rollingInterval: RollingInterval.Day) 85 rollingInterval: RollingInterval.Day)
83 .CreateLogger(); 86 .CreateLogger();
84   87  
85 // Start application update. 88 // Start application update.
86 var manifestModuleName = Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName; 89 var manifestModuleName = Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName;
87 var icon = Icon.ExtractAssociatedIcon(manifestModuleName); 90 var icon = Icon.ExtractAssociatedIcon(manifestModuleName);
88   91  
89 _sparkle = new SparkleUpdater("https://winify.grimore.org/update/appcast.xml", 92 _sparkle = new SparkleUpdater("https://winify.grimore.org/update/appcast.xml",
90 new Ed25519Checker(SecurityMode.Strict, "LonrgxVjSF0GnY4hzwlRJnLkaxnDn2ikdmOifILzLJY=")) 93 new Ed25519Checker(SecurityMode.Strict, "LonrgxVjSF0GnY4hzwlRJnLkaxnDn2ikdmOifILzLJY="))
91 { 94 {
92 UIFactory = new UIFactory(icon), 95 UIFactory = new UIFactory(icon),
93 RelaunchAfterUpdate = true, 96 RelaunchAfterUpdate = true,
94 SecurityProtocolType = SecurityProtocolType.Tls12 97 SecurityProtocolType = SecurityProtocolType.Tls12
95 }; 98 };
96 _sparkle.StartLoop(true, true); 99 _sparkle.StartLoop(true, true);
97 } 100 }
98   101  
99 /// <summary> 102 /// <summary>
100 /// Clean up any resources being used. 103 /// Clean up any resources being used.
101 /// </summary> 104 /// </summary>
102 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 105 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
103 protected override void Dispose(bool disposing) 106 protected override void Dispose(bool disposing)
104 { 107 {
105 if (disposing && components != null) components.Dispose(); 108 if (disposing && components != null) components.Dispose();
106   109  
107 base.Dispose(disposing); 110 base.Dispose(disposing);
108 } 111 }
109   112  
110 #endregion 113 #endregion
111   114  
112 #region Event Handlers 115 #region Event Handlers
-   116  
-   117 private async void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
-   118 {
-   119 switch (e.Mode)
-   120 {
-   121 case PowerModes.Resume:
-   122 // Refresh connection to gotify server.
-   123 while (_gotifyConnections.TryTake(out var gotifyConnection))
-   124 {
-   125 gotifyConnection.GotifyMessage -= GotifyConnectionGotifyMessage;
-   126 await gotifyConnection.Stop();
-   127 gotifyConnection.Dispose();
-   128 }
-   129  
-   130 var servers = await LoadServers();
-   131 foreach (var server in servers.Server)
-   132 {
-   133 var gotifyConnection = new GotifyConnection(server, Configuration);
-   134 gotifyConnection.GotifyMessage += GotifyConnectionGotifyMessage;
-   135 gotifyConnection.Start();
-   136 _gotifyConnections.Add(gotifyConnection);
-   137 }
-   138 break;
-   139 }
-   140 }
113   141  
114 private async void MainForm_Load(object sender, EventArgs e) 142 private async void MainForm_Load(object sender, EventArgs e)
115 { 143 {
116 Configuration = await LoadConfiguration(); 144 Configuration = await LoadConfiguration();
117   145  
118 var servers = await LoadServers(); 146 var servers = await LoadServers();
119 _gotifyConnections = new ConcurrentBag<GotifyConnection>(); 147 _gotifyConnections = new ConcurrentBag<GotifyConnection>();
120 foreach (var server in servers.Server) 148 foreach (var server in servers.Server)
121 { 149 {
122 var gotifyConnection = new GotifyConnection(server, Configuration); 150 var gotifyConnection = new GotifyConnection(server, Configuration);
123 gotifyConnection.GotifyMessage += GotifyConnectionGotifyMessage; 151 gotifyConnection.GotifyMessage += GotifyConnectionGotifyMessage;
124 gotifyConnection.Start(); 152 gotifyConnection.Start();
125 _gotifyConnections.Add(gotifyConnection); 153 _gotifyConnections.Add(gotifyConnection);
126 } 154 }
127 } 155 }
128   156  
129 private void LogViewToolStripMenuItem_Click(object sender, EventArgs e) 157 private void LogViewToolStripMenuItem_Click(object sender, EventArgs e)
130 { 158 {
131 if (_logViewForm != null) 159 if (_logViewForm != null)
132 { 160 {
133 return; 161 return;
134 } 162 }
135   163  
136 _logViewForm = new LogViewForm(this, _memorySink, _cancellationToken); 164 _logViewForm = new LogViewForm(this, _memorySink, _cancellationToken);
137 _logViewForm.Closing += LogViewForm_Closing; 165 _logViewForm.Closing += LogViewForm_Closing;
138 _logViewForm.Show(); 166 _logViewForm.Show();
139 } 167 }
140   168  
141 private void LogViewForm_Closing(object sender, CancelEventArgs e) 169 private void LogViewForm_Closing(object sender, CancelEventArgs e)
142 { 170 {
143 if (_logViewForm == null) 171 if (_logViewForm == null)
144 { 172 {
145 return; 173 return;
146 } 174 }
147   175  
148 _logViewForm.Closing -= LogViewForm_Closing; 176 _logViewForm.Closing -= LogViewForm_Closing;
149 _logViewForm.Close(); 177 _logViewForm.Close();
150 _logViewForm = null; 178 _logViewForm = null;
151 } 179 }
152   180  
153 private async void SettingsToolStripMenuItem_Click(object sender, EventArgs e) 181 private async void SettingsToolStripMenuItem_Click(object sender, EventArgs e)
154 { 182 {
155 if (_settingsForm == null) 183 if (_settingsForm == null)
156 { 184 {
157 var servers = await LoadServers(); 185 var servers = await LoadServers();
158 var announcements = await LoadAnnouncements(); 186 var announcements = await LoadAnnouncements();
159   187  
160 _settingsForm = new SettingsForm(this, servers, announcements, _cancellationToken); 188 _settingsForm = new SettingsForm(this, servers, announcements, _cancellationToken);
161 _settingsForm.Save += SettingsForm_Save; 189 _settingsForm.Save += SettingsForm_Save;
162 _settingsForm.Closing += SettingsForm_Closing; 190 _settingsForm.Closing += SettingsForm_Closing;
163 _settingsForm.Show(); 191 _settingsForm.Show();
164 } 192 }
165 } 193 }
166   194  
167 private async void SettingsForm_Save(object sender, SettingsSavedEventArgs e) 195 private async void SettingsForm_Save(object sender, SettingsSavedEventArgs e)
168 { 196 {
169 // Save the configuration. 197 // Save the configuration.
170 Miscellaneous.LaunchOnBootSet(Configuration.LaunchOnBoot); 198 Miscellaneous.LaunchOnBootSet(Configuration.LaunchOnBoot);
171 ChangedConfigurationContinuation.Schedule(TimeSpan.FromSeconds(1), 199 ChangedConfigurationContinuation.Schedule(TimeSpan.FromSeconds(1),
172 async () => { await SaveConfiguration(); }, _cancellationToken); 200 async () => { await SaveConfiguration(); }, _cancellationToken);
173   201  
174 // Save the servers. 202 // Save the servers.
175 await Task.WhenAll(SaveServers(e.Servers), SaveAnnouncements(e.Announcements)); 203 await Task.WhenAll(SaveServers(e.Servers), SaveAnnouncements(e.Announcements));
176   204  
177 // Update connections to gotify servers. 205 // Update connections to gotify servers.
178 while (_gotifyConnections.TryTake(out var gotifyConnection)) 206 while (_gotifyConnections.TryTake(out var gotifyConnection))
179 { 207 {
180 gotifyConnection.GotifyMessage -= GotifyConnectionGotifyMessage; 208 gotifyConnection.GotifyMessage -= GotifyConnectionGotifyMessage;
181 await gotifyConnection.Stop(); 209 await gotifyConnection.Stop();
182 gotifyConnection.Dispose(); 210 gotifyConnection.Dispose();
183 } 211 }
184   212  
185 foreach (var server in e.Servers.Server) 213 foreach (var server in e.Servers.Server)
186 { 214 {
187 var gotifyConnection = new GotifyConnection(server, Configuration); 215 var gotifyConnection = new GotifyConnection(server, Configuration);
188 gotifyConnection.GotifyMessage += GotifyConnectionGotifyMessage; 216 gotifyConnection.GotifyMessage += GotifyConnectionGotifyMessage;
189 gotifyConnection.Start(); 217 gotifyConnection.Start();
190 _gotifyConnections.Add(gotifyConnection); 218 _gotifyConnections.Add(gotifyConnection);
191 } 219 }
192 } 220 }
193   221  
194 private async void GotifyConnectionGotifyMessage(object sender, GotifyMessageEventArgs e) 222 private async void GotifyConnectionGotifyMessage(object sender, GotifyMessageEventArgs e)
195 { 223 {
196 var announcements = await LoadAnnouncements(); 224 var announcements = await LoadAnnouncements();
197   225  
198 foreach (var announcement in announcements.Announcement) 226 foreach (var announcement in announcements.Announcement)
199 { 227 {
200 if (announcement.AppId != e.Message.AppId) 228 if (announcement.AppId != e.Message.AppId)
201 { 229 {
202 continue; 230 continue;
203 } 231 }
204   232  
205 if (announcement.Ignore) 233 if (announcement.Ignore)
206 { 234 {
207 return; 235 return;
208 } 236 }
209   237  
210 if (announcement.LingerTime <= 0) 238 if (announcement.LingerTime <= 0)
211 { 239 {
212 return; 240 return;
213 } 241 }
214   242  
215 var configuredNotification = new ToastForm( 243 var configuredNotification = new ToastForm(
216 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})", 244 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})",
217 e.Message.Message) 245 e.Message.Message)
218 { 246 {
219 EnableChime = announcement.EnableChime, 247 EnableChime = announcement.EnableChime,
220 Chime = announcement.Chime ?? Configuration.Chime, 248 Chime = announcement.Chime ?? Configuration.Chime,
221 LingerTime = (int)announcement.LingerTime, 249 LingerTime = (int)announcement.LingerTime,
222 Image = e.Image 250 Image = e.Image
223 }; 251 };
224   252  
225 await _toasts.Queue(configuredNotification); 253 await _toasts.Queue(configuredNotification);
226   254  
227 return; 255 return;
228 } 256 }
229   257  
230 if (Configuration.InfiniteToastDuration) 258 if (Configuration.InfiniteToastDuration)
231 { 259 {
232 var infiniteToastForm = new ToastForm( 260 var infiniteToastForm = new ToastForm(
233 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})", 261 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})",
234 e.Message.Message) 262 e.Message.Message)
235 { 263 {
236 Chime = Configuration.Chime, 264 Chime = Configuration.Chime,
237 Image = e.Image 265 Image = e.Image
238 }; 266 };
239   267  
240 await _toasts.Queue(infiniteToastForm); 268 await _toasts.Queue(infiniteToastForm);
241   269  
242 return; 270 return;
243 } 271 }
244   272  
245 var toastForm = new ToastForm( 273 var toastForm = new ToastForm(
246 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})", 274 $"{e.Message.Title} ({e.Message.Server.Name}/{e.Message.AppId})",
247 e.Message.Message) 275 e.Message.Message)
248 { 276 {
249 Chime = Configuration.Chime, 277 Chime = Configuration.Chime,
250 LingerTime = Configuration.ToastDuration, 278 LingerTime = Configuration.ToastDuration,
251 Image = e.Image 279 Image = e.Image
252 }; 280 };
253   281  
254 await _toasts.Queue(toastForm); 282 await _toasts.Queue(toastForm);
255 } 283 }
256   284  
257 private void SettingsForm_Closing(object sender, CancelEventArgs e) 285 private void SettingsForm_Closing(object sender, CancelEventArgs e)
258 { 286 {
259 if (_settingsForm == null) 287 if (_settingsForm == null)
260 { 288 {
261 return; 289 return;
262 } 290 }
263   291  
264 _settingsForm.Save -= SettingsForm_Save; 292 _settingsForm.Save -= SettingsForm_Save;
265 _settingsForm.Closing -= SettingsForm_Closing; 293 _settingsForm.Closing -= SettingsForm_Closing;
266 _settingsForm.Dispose(); 294 _settingsForm.Dispose();
267 _settingsForm = null; 295 _settingsForm = null;
268 } 296 }
269   297  
270 private void AboutToolStripMenuItem_Click(object sender, EventArgs e) 298 private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
271 { 299 {
272 if (_aboutForm != null) 300 if (_aboutForm != null)
273 { 301 {
274 return; 302 return;
275 } 303 }
276   304  
277 _aboutForm = new AboutForm(); 305 _aboutForm = new AboutForm();
278 _aboutForm.Closing += AboutForm_Closing; 306 _aboutForm.Closing += AboutForm_Closing;
279 _aboutForm.Show(); 307 _aboutForm.Show();
280 } 308 }
281   309  
282 private void AboutForm_Closing(object sender, CancelEventArgs e) 310 private void AboutForm_Closing(object sender, CancelEventArgs e)
283 { 311 {
284 if (_aboutForm == null) 312 if (_aboutForm == null)
285 { 313 {
286 return; 314 return;
287 } 315 }
288   316  
289 _aboutForm.Closing -= AboutForm_Closing; 317 _aboutForm.Closing -= AboutForm_Closing;
290 _aboutForm.Dispose(); 318 _aboutForm.Dispose();
291 _aboutForm = null; 319 _aboutForm = null;
292 } 320 }
293   321  
294 private void QuitToolStripMenuItem_Click(object sender, EventArgs e) 322 private void QuitToolStripMenuItem_Click(object sender, EventArgs e)
295 { 323 {
296 Close(); 324 Close();
297 } 325 }
298   326  
299 private async void UpdateToolStripMenuItem_Click(object sender, EventArgs e) 327 private async void UpdateToolStripMenuItem_Click(object sender, EventArgs e)
300 { 328 {
301 // Manually check for updates, this will not show a ui 329 // Manually check for updates, this will not show a ui
302 var result = await _sparkle.CheckForUpdatesQuietly(); 330 var result = await _sparkle.CheckForUpdatesQuietly();
303 var updates = result.Updates; 331 var updates = result.Updates;
304 if (result.Status == UpdateStatus.UpdateAvailable) 332 if (result.Status == UpdateStatus.UpdateAvailable)
305 { 333 {
306 // if update(s) are found, then we have to trigger the UI to show it gracefully 334 // if update(s) are found, then we have to trigger the UI to show it gracefully
307 _sparkle.ShowUpdateNeededUI(); 335 _sparkle.ShowUpdateNeededUI();
308 return; 336 return;
309 } 337 }
310   338  
311 MessageBox.Show("No updates available at this time.", "Winify", MessageBoxButtons.OK, 339 MessageBox.Show("No updates available at this time.", "Winify", MessageBoxButtons.OK,
312 MessageBoxIcon.Asterisk, 340 MessageBoxIcon.Asterisk,
313 MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false); 341 MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
314 } 342 }
315   343  
316 #endregion 344 #endregion
317   345  
318 #region Public Methods 346 #region Public Methods
319   347  
320 public async Task SaveConfiguration() 348 public async Task SaveConfiguration()
321 { 349 {
322 if (!Directory.Exists(Constants.UserApplicationDirectory)) 350 if (!Directory.Exists(Constants.UserApplicationDirectory))
323 Directory.CreateDirectory(Constants.UserApplicationDirectory); 351 Directory.CreateDirectory(Constants.UserApplicationDirectory);
324   352  
325 switch (await Serialization.Serialize(Configuration, Constants.ConfigurationFile, "Configuration", 353 switch (await Serialization.Serialize(Configuration, Constants.ConfigurationFile, "Configuration",
326 "<!ATTLIST Configuration xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>", 354 "<!ATTLIST Configuration xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
327 CancellationToken.None)) 355 CancellationToken.None))
328 { 356 {
329 case SerializationSuccess<Configuration.Configuration> _: 357 case SerializationSuccess<Configuration.Configuration> _:
330 Log.Information("Serialized configuration."); 358 Log.Information("Serialized configuration.");
331 break; 359 break;
332 case SerializationFailure serializationFailure: 360 case SerializationFailure serializationFailure:
333 Log.Warning(serializationFailure.Exception.Message, "Failed to serialize configuration."); 361 Log.Warning(serializationFailure.Exception.Message, "Failed to serialize configuration.");
334 break; 362 break;
335 } 363 }
336 } 364 }
337   365  
338 public static async Task<Configuration.Configuration> LoadConfiguration() 366 public static async Task<Configuration.Configuration> LoadConfiguration()
339 { 367 {
340 if (!Directory.Exists(Constants.UserApplicationDirectory)) 368 if (!Directory.Exists(Constants.UserApplicationDirectory))
341 Directory.CreateDirectory(Constants.UserApplicationDirectory); 369 Directory.CreateDirectory(Constants.UserApplicationDirectory);
342   370  
343 var deserializationResult = 371 var deserializationResult =
344 await Serialization.Deserialize<Configuration.Configuration>(Constants.ConfigurationFile, 372 await Serialization.Deserialize<Configuration.Configuration>(Constants.ConfigurationFile,
345 Constants.ConfigurationNamespace, Constants.ConfigurationXsd, CancellationToken.None); 373 Constants.ConfigurationNamespace, Constants.ConfigurationXsd, CancellationToken.None);
346   374  
347 switch (deserializationResult) 375 switch (deserializationResult)
348 { 376 {
349 case SerializationSuccess<Configuration.Configuration> serializationSuccess: 377 case SerializationSuccess<Configuration.Configuration> serializationSuccess:
350 return serializationSuccess.Result; 378 return serializationSuccess.Result;
351 case SerializationFailure serializationFailure: 379 case SerializationFailure serializationFailure:
352 Log.Warning(serializationFailure.Exception, "Failed to load configuration."); 380 Log.Warning(serializationFailure.Exception, "Failed to load configuration.");
353 return new Configuration.Configuration(); 381 return new Configuration.Configuration();
354 default: 382 default:
355 return new Configuration.Configuration(); 383 return new Configuration.Configuration();
356 } 384 }
357 } 385 }
358   386  
359 #endregion 387 #endregion
360   388  
361 #region Private Methods 389 #region Private Methods
362   390  
363 private static async Task SaveAnnouncements(Announcements.Announcements announcements) 391 private static async Task SaveAnnouncements(Announcements.Announcements announcements)
364 { 392 {
365 switch (await Serialization.Serialize(announcements, Constants.AnnouncementsFile, "Announcements", 393 switch (await Serialization.Serialize(announcements, Constants.AnnouncementsFile, "Announcements",
366 "<!ATTLIST Announcements xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>", 394 "<!ATTLIST Announcements xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
367 CancellationToken.None)) 395 CancellationToken.None))
368 { 396 {
369 case SerializationFailure serializationFailure: 397 case SerializationFailure serializationFailure:
370 Log.Warning(serializationFailure.Exception, "Unable to serialize announcements."); 398 Log.Warning(serializationFailure.Exception, "Unable to serialize announcements.");
371 break; 399 break;
372 } 400 }
373 } 401 }
374   402  
375 private static async Task SaveServers(Servers.Servers servers) 403 private static async Task SaveServers(Servers.Servers servers)
376 { 404 {
377 // Encrypt password for all servers. 405 // Encrypt password for all servers.
378 var deviceId = Miscellaneous.GetMachineGuid(); 406 var deviceId = Miscellaneous.GetMachineGuid();
379 var @protected = new Servers.Servers 407 var @protected = new Servers.Servers
380 { 408 {
381 Server = new BindingListWithCollectionChanged<Server>() 409 Server = new BindingListWithCollectionChanged<Server>()
382 }; 410 };
383   411  
384 foreach (var server in servers.Server) 412 foreach (var server in servers.Server)
385 { 413 {
386 var password = Encoding.UTF8.GetBytes(server.Password); 414 var password = Encoding.UTF8.GetBytes(server.Password);
387 var encrypted = await AES.Encrypt(password, deviceId); 415 var encrypted = await AES.Encrypt(password, deviceId);
388 var armored = Convert.ToBase64String(encrypted); 416 var armored = Convert.ToBase64String(encrypted);
389   417  
390 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, armored)); 418 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, armored));
391 } 419 }
392   420  
393 switch (await Serialization.Serialize(@protected, Constants.ServersFile, "Servers", 421 switch (await Serialization.Serialize(@protected, Constants.ServersFile, "Servers",
394 "<!ATTLIST Servers xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>", 422 "<!ATTLIST Servers xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
395 CancellationToken.None)) 423 CancellationToken.None))
396 { 424 {
397 case SerializationFailure serializationFailure: 425 case SerializationFailure serializationFailure:
398 Log.Warning(serializationFailure.Exception, "Unable to serialize servers."); 426 Log.Warning(serializationFailure.Exception, "Unable to serialize servers.");
399 break; 427 break;
400 } 428 }
401 } 429 }
402   430  
403 private static async Task<Announcements.Announcements> LoadAnnouncements() 431 private static async Task<Announcements.Announcements> LoadAnnouncements()
404 { 432 {
405 if (!Directory.Exists(Constants.UserApplicationDirectory)) 433 if (!Directory.Exists(Constants.UserApplicationDirectory))
406 Directory.CreateDirectory(Constants.UserApplicationDirectory); 434 Directory.CreateDirectory(Constants.UserApplicationDirectory);
407   435  
408 var deserializationResult = 436 var deserializationResult =
409 await Serialization.Deserialize<Announcements.Announcements>(Constants.AnnouncementsFile, 437 await Serialization.Deserialize<Announcements.Announcements>(Constants.AnnouncementsFile,
410 "urn:winify-announcements-schema", "Announcements.xsd", CancellationToken.None); 438 "urn:winify-announcements-schema", "Announcements.xsd", CancellationToken.None);
411   439  
412 switch (deserializationResult) 440 switch (deserializationResult)
413 { 441 {
414 case SerializationSuccess<Announcements.Announcements> serializationSuccess: 442 case SerializationSuccess<Announcements.Announcements> serializationSuccess:
415 return serializationSuccess.Result; 443 return serializationSuccess.Result;
416 case SerializationFailure serializationFailure: 444 case SerializationFailure serializationFailure:
417 Log.Warning(serializationFailure.Exception, "Unable to load announcements."); 445 Log.Warning(serializationFailure.Exception, "Unable to load announcements.");
418 return new Announcements.Announcements(); 446 return new Announcements.Announcements();
419 default: 447 default:
420 return new Announcements.Announcements(); 448 return new Announcements.Announcements();
421 } 449 }
422 } 450 }
423   451  
424 private static async Task<Servers.Servers> LoadServers() 452 private static async Task<Servers.Servers> LoadServers()
425 { 453 {
426 if (!Directory.Exists(Constants.UserApplicationDirectory)) 454 if (!Directory.Exists(Constants.UserApplicationDirectory))
427 Directory.CreateDirectory(Constants.UserApplicationDirectory); 455 Directory.CreateDirectory(Constants.UserApplicationDirectory);
428   456  
429 var deserializationResult = 457 var deserializationResult =
430 await Serialization.Deserialize<Servers.Servers>(Constants.ServersFile, 458 await Serialization.Deserialize<Servers.Servers>(Constants.ServersFile,
431 "urn:winify-servers-schema", "Servers.xsd", CancellationToken.None); 459 "urn:winify-servers-schema", "Servers.xsd", CancellationToken.None);
432   460  
433 switch (deserializationResult) 461 switch (deserializationResult)
434 { 462 {
435 case SerializationSuccess<Servers.Servers> serializationSuccess: 463 case SerializationSuccess<Servers.Servers> serializationSuccess:
436 // Decrypt password. 464 // Decrypt password.
437 var deviceId = Miscellaneous.GetMachineGuid(); 465 var deviceId = Miscellaneous.GetMachineGuid();
438 var @protected = new Servers.Servers 466 var @protected = new Servers.Servers
439 { 467 {
440 Server = new BindingListWithCollectionChanged<Server>() 468 Server = new BindingListWithCollectionChanged<Server>()
441 }; 469 };
442 foreach (var server in serializationSuccess.Result.Server) 470 foreach (var server in serializationSuccess.Result.Server)
443 { 471 {
444 var unarmored = Convert.FromBase64String(server.Password); 472 var unarmored = Convert.FromBase64String(server.Password);
445 byte[] decrypted; 473 byte[] decrypted;
446 try 474 try
447 { 475 {
448 decrypted = await AES.Decrypt(unarmored, deviceId); 476 decrypted = await AES.Decrypt(unarmored, deviceId);
449 } 477 }
450 catch(Exception exception) 478 catch(Exception exception)
451 { 479 {
452 Log.Warning(exception, $"Could not decrypt password for server {server.Name} in configuration file."); 480 Log.Warning(exception, $"Could not decrypt password for server {server.Name} in configuration file.");
453 continue; 481 continue;
454 } 482 }
455   483  
456 var password = Encoding.UTF8.GetString(decrypted); 484 var password = Encoding.UTF8.GetString(decrypted);
457   485  
458 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, password)); 486 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, password));
459 } 487 }
460   488  
461 return @protected; 489 return @protected;
462   490  
463 case SerializationFailure serializationFailure: 491 case SerializationFailure serializationFailure:
464 Log.Warning(serializationFailure.Exception, "Unable to load servers."); 492 Log.Warning(serializationFailure.Exception, "Unable to load servers.");
465 return new Servers.Servers(); 493 return new Servers.Servers();
466   494  
467 default: 495 default:
468 return new Servers.Servers(); 496 return new Servers.Servers();
469 } 497 }
470 } 498 }
471   499  
472 #endregion 500 #endregion
473 } 501 }
474 } 502 }
475   503  
476
Generated by GNU Enscript 1.6.5.90.
504
Generated by GNU Enscript 1.6.5.90.
477   505  
478   506  
479   507