-
Notifications
You must be signed in to change notification settings - Fork 1
/
MainForm.cs
751 lines (681 loc) · 26 KB
/
MainForm.cs
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//-----------------------------------------------------------------------
// <copyright file="MainForm.cs" company="Michael Kourlas">
// namecheap-dynamic-dns
// Copyright (C) 2017 Michael Kourlas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Kourlas.NamecheapDynamicDns
{
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using Kourlas.NamecheapDynamicDns.Properties;
/// <summary>
/// The main form of the application.
/// </summary>
public partial class MainForm : Form
{
/// <summary>
/// Handles the performance and scheduling of dynamic DNS updates and
/// informs the UI when they are complete using an event handler.
/// </summary>
private DynamicDns dynamicDns;
/// <summary>
/// The current mode that the Profiles tab is in.
/// </summary>
private ProfilesMode mode;
/// <summary>
/// Initializes a new instance of the <see cref="MainForm"/> class.
/// </summary>
public MainForm()
{
this.InitializeComponent();
this.ChangeMode(ProfilesMode.NONE);
this.dynamicDns = new DynamicDns();
this.dynamicDns.DynamicDnsUpdateEventHandler +=
this.OnDynamicDnsUpdate;
this.LoadProfiles();
this.labelProductName.Text = this.AssemblyProduct;
this.labelVersion.Text = string.Format(
"Version {0}", this.AssemblyVersion);
this.labelCopyright.Text = this.AssemblyCopyright;
this.labelCompanyName.Text = this.AssemblyCompany;
this.textBoxDescription.Text = this.AssemblyDescription;
}
/// <summary>
/// Represents the mode that the Profiles tab is in.
/// </summary>
private enum ProfilesMode
{
/// <summary>
/// None mode. The Profiles tab is unused.
/// </summary>
NONE,
/// <summary>
/// New mode. The Profiles tab is being used to create a new
/// profile.
/// </summary>
NEW,
/// <summary>
/// Edit mode. The Profiles tab is being used to edit a profile.
/// </summary>
EDIT
}
#region Assembly Attribute Accessors
/// <summary>
/// Gets the assembly title.
/// </summary>
public string AssemblyTitle
{
get
{
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0)
{
AssemblyTitleAttribute titleAttribute =
(AssemblyTitleAttribute)attributes[0];
if (titleAttribute.Title != string.Empty)
{
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(
Assembly.GetExecutingAssembly().CodeBase);
}
}
/// <summary>
/// Gets the assembly version.
/// </summary>
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version
.ToString();
}
}
/// <summary>
/// Gets the assembly description.
/// </summary>
public string AssemblyDescription
{
get
{
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyDescriptionAttribute), false);
if (attributes.Length == 0)
{
return string.Empty;
}
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
/// <summary>
/// Gets the assembly product.
/// </summary>
public string AssemblyProduct
{
get
{
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyProductAttribute), false);
if (attributes.Length == 0)
{
return string.Empty;
}
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
/// <summary>
/// Gets the assembly copyright.
/// </summary>
public string AssemblyCopyright
{
get
{
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0)
{
return string.Empty;
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
/// <summary>
/// Gets the assembly company.
/// </summary>
public string AssemblyCompany
{
get
{
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0)
{
return string.Empty;
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
/// <summary>
/// Changes the application mode to the specified mode.
/// </summary>
/// <param name="mode">The specified mode.</param>
private void ChangeMode(ProfilesMode mode)
{
switch (mode)
{
case ProfilesMode.NONE:
this.ChangeToNoneMode();
break;
case ProfilesMode.NEW:
this.ChangeToNewMode();
break;
case ProfilesMode.EDIT:
this.ChangeToEditMode();
break;
}
}
/// <summary>
/// Changes the application mode to the none mode.
/// </summary>
private void ChangeToNoneMode()
{
profilesComboBox.SelectedIndex = -1;
hostTextBox.Enabled = false;
hostTextBox.Text = string.Empty;
domainTextBox.Enabled = false;
domainTextBox.Text = string.Empty;
dynamicDnsPasswordTextBox.Enabled = false;
dynamicDnsPasswordTextBox.Text = string.Empty;
updateIntervalComboBox.Enabled = false;
updateIntervalComboBox.SelectedIndex = -1;
autoDetectCheckBox.Enabled = false;
autoDetectCheckBox.Checked = false;
ipAddressTextBox.Enabled = false;
ipAddressTextBox.Text = string.Empty;
deleteButton.Enabled = false;
saveButton.Enabled = false;
cancelButton.Enabled = false;
this.mode = ProfilesMode.NONE;
}
/// <summary>
/// Changes the application mode to the new mode.
/// </summary>
private void ChangeToNewMode()
{
profilesComboBox.SelectedIndex = -1;
hostTextBox.Enabled = true;
hostTextBox.Text = string.Empty;
domainTextBox.Enabled = true;
domainTextBox.Text = string.Empty;
dynamicDnsPasswordTextBox.Enabled = true;
dynamicDnsPasswordTextBox.Text = string.Empty;
updateIntervalComboBox.Enabled = true;
updateIntervalComboBox.SelectedIndex =
updateIntervalComboBox.Items.Count - 1;
autoDetectCheckBox.Enabled = true;
autoDetectCheckBox.Checked = false;
ipAddressTextBox.Enabled = true;
ipAddressTextBox.Text = string.Empty;
deleteButton.Enabled = true;
saveButton.Enabled = true;
cancelButton.Enabled = true;
this.mode = ProfilesMode.NEW;
}
/// <summary>
/// Changes the application mode to the edit mode.
/// </summary>
private void ChangeToEditMode()
{
var id = ((ComboBoxItem)profilesComboBox
.Items[profilesComboBox.SelectedIndex]).Id;
var profile = this.dynamicDns.GetProfile(id);
if (profile == null)
{
return;
}
hostTextBox.Enabled = true;
hostTextBox.Text = profile.Host;
domainTextBox.Enabled = true;
domainTextBox.Text = profile.Domain;
dynamicDnsPasswordTextBox.Enabled = true;
dynamicDnsPasswordTextBox.Text = profile.DynamicDnsPassword;
updateIntervalComboBox.Enabled = true;
updateIntervalComboBox.SelectedIndex = (int)profile.Interval;
autoDetectCheckBox.Enabled = true;
autoDetectCheckBox.Checked = profile.AutoDetectIPAddress;
ipAddressTextBox.Enabled = !profile.AutoDetectIPAddress;
ipAddressTextBox.Text = profile.UpdateIPAddress?.ToString() ??
string.Empty;
if (autoDetectCheckBox.Checked)
{
ipAddressTextBox.Text = string.Empty;
}
deleteButton.Enabled = true;
saveButton.Enabled = true;
cancelButton.Enabled = true;
this.mode = ProfilesMode.EDIT;
}
/// <summary>
/// Adds the specified profile to the profiles list.
/// </summary>
/// <param name="profile">The specified profile.</param>
/// <returns>A task which completes when the process is
/// complete.</returns>
private async Task AddProfile(DynamicDnsProfile profile)
{
var statusItem = new ListViewItem(profile.Label)
{
Tag = profile.Id
};
statusItem.SubItems.Add(new ListViewItem.ListViewSubItem(
statusItem, string.Empty));
statusItem.SubItems.Add(new ListViewItem.ListViewSubItem(
statusItem, string.Empty));
this.statusListView.Items.Add(statusItem);
var profileItem = new ComboBoxItem(profile.Label, profile.Id);
this.profilesComboBox.Items.Add(profileItem);
await this.dynamicDns.AddProfile(profile);
}
/// <summary>
/// Replaces the old profile with the specified ID with the specified
/// new profile.
/// </summary>
/// <param name="oldProfileId">The ID of the old profile.</param>
/// <param name="newProfile">The new profile.</param>
/// <returns>A task which completes when the process is
/// complete.</returns>
private async Task ReplaceProfile(
Guid oldProfileId,
DynamicDnsProfile newProfile)
{
this.DeleteProfile(oldProfileId);
await this.AddProfile(newProfile);
}
/// <summary>
/// Deletes the specified profile.
/// </summary>
/// <param name="profileId">The ID of the profile to delete.</param>
private void DeleteProfile(Guid profileId)
{
var statusItems = statusListView.Items.Cast<ListViewItem>();
var statusItemQuery = from item in statusItems
where (Guid)item.Tag == profileId
select item;
var statusItemsList = statusItemQuery.ToList();
foreach (var item in statusItemsList)
{
statusListView.Items.Remove(item);
}
var profileItems = profilesComboBox.Items.Cast<ComboBoxItem>();
var profileItemQuery = from item in profileItems
where (Guid)item.Id == profileId
select item;
var profileItemsList = profileItemQuery.ToList();
foreach (var item in profileItemsList)
{
profilesComboBox.Items.Remove(item);
}
this.dynamicDns.DeleteProfile(profileId);
}
/// <summary>
/// Loads the dynamic DNS profiles from the application settings.
/// If deserialization fails, does nothing.
/// </summary>
/// <returns>A task which completes when the process is
/// complete.</returns>
private async void LoadProfiles()
{
try
{
if (Settings.Default.SettingsUpgradeRequired)
{
Settings.Default.Upgrade();
Settings.Default.SettingsUpgradeRequired = false;
Settings.Default.Save();
}
if (Settings.Default.Profiles != null)
{
var xmlSerializer = new XmlSerializer(
typeof(DynamicDnsProfile));
foreach (string profileString in Settings.Default.Profiles)
{
var profileStream = new MemoryStream(
Encoding.UTF8.GetBytes(profileString));
var profileStreamReader = new StreamReader(
profileStream, Encoding.UTF8);
var profile = (DynamicDnsProfile)
xmlSerializer.Deserialize(profileStreamReader);
await this.AddProfile(profile);
}
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to load profiles: {ex.Message}.",
"namecheap-dynamic-dns");
}
}
/// <summary>
/// Saves the dynamic DNS profiles to the application settings.
/// If serialization fails, does nothing.
/// </summary>
private void SaveProfiles()
{
try
{
// Serialize each profile to an XML string (encoded using
// UTF-8) and add them to a string collection
var collection = new StringCollection();
var xmlSerializer = new XmlSerializer(
typeof(DynamicDnsProfile));
foreach (DynamicDnsProfile profile
in this.dynamicDns.Profiles.Values)
{
using (var profileStream = new MemoryStream())
{
var profileStreamWriter = new StreamWriter(
profileStream,
Encoding.UTF8);
xmlSerializer.Serialize(profileStreamWriter, profile);
var profileString = Encoding.UTF8.GetString(
profileStream.ToArray());
collection.Add(profileString);
}
}
// Replace existing string collection with new string
// collection and save to settings
Settings.Default.Profiles = collection;
Settings.Default.Save();
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to save profiles: {ex.Message}.",
"namecheap-dynamic-dns");
}
}
/// <summary>
/// Called when a dynamic DNS update occurs.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnDynamicDnsUpdate(
object sender, DynamicDnsUpdateEventArgs e)
{
var date = e.UpdateDateTime.ToShortDateString() + " " +
e.UpdateDateTime.ToShortTimeString();
var message = e.Success ?
$"Update successful ({e.Ip})" :
$"Update failed ({e.UpdateException.Message})";
var items = statusListView.Items.Cast<ListViewItem>();
var statusItemQuery = from item in items
where (Guid)item.Tag == e.UpdateProfile.Id
select item;
var statusItems = statusItemQuery.ToList();
if (statusItems.Count == 1)
{
var statusItem = statusItems[0];
statusItem.SubItems[1].Text = message;
statusItem.SubItems[2].Text = date;
lastActionValueStatusLabel.Text =
$"{e.UpdateProfile.Label} ({date})";
}
}
/// <summary>
/// Called when the Update button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private async void OnUpdateButtonClick(object sender, EventArgs e)
{
foreach (int index in statusListView.SelectedIndices)
{
var item = this.statusListView.Items[index];
var profile = this.dynamicDns.GetProfile((Guid)item.Tag);
if (profile != null)
{
await this.dynamicDns.PerformUpdate(profile);
}
}
}
/// <summary>
/// Called when the Update All button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private async void OnUpdateAllButtonClick(object sender, EventArgs e)
{
await this.dynamicDns.PerformUpdateAll();
}
/// <summary>
/// Called when the New button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnNewButtonClick(object sender, EventArgs e)
{
this.ChangeMode(ProfilesMode.NEW);
}
/// <summary>
/// Called when the Delete button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnDeleteButtonClick(object sender, EventArgs e)
{
if (this.mode != ProfilesMode.NEW)
{
var id = ((ComboBoxItem)profilesComboBox
.Items[profilesComboBox.SelectedIndex]).Id;
this.DeleteProfile(id);
}
this.ChangeMode(ProfilesMode.NONE);
}
/// <summary>
/// Called when the Save button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private async void OnSaveButtonClick(object sender, EventArgs e)
{
var mode = this.mode;
var index = profilesComboBox.SelectedIndex;
var profile = new DynamicDnsProfile()
{
Host = hostTextBox.Text,
Domain = domainTextBox.Text,
DynamicDnsPassword = dynamicDnsPasswordTextBox.Text,
Interval =
(UpdateInterval)updateIntervalComboBox.SelectedIndex
};
IPAddress.TryParse(ipAddressTextBox.Text, out IPAddress ipAddress);
profile.UpdateIPAddress = ipAddress?.ToString() ?? string.Empty;
profile.AutoDetectIPAddress = autoDetectCheckBox.Checked;
if (profile.Host == string.Empty || profile.Domain == string.Empty
|| profile.DynamicDnsPassword == string.Empty
|| updateIntervalComboBox.SelectedIndex == -1
|| (profile.UpdateIPAddress == string.Empty
&& !profile.AutoDetectIPAddress))
{
MessageBox.Show(
"Profile information validation failed.",
"namecheap-dynamic-dns");
return;
}
this.ChangeMode(ProfilesMode.NONE);
if (mode == ProfilesMode.NEW)
{
await this.AddProfile(profile);
}
else if (mode == ProfilesMode.EDIT)
{
var id = ((ComboBoxItem)profilesComboBox.Items[index]).Id;
await this.ReplaceProfile(id, profile);
}
}
/// <summary>
/// Called when the Cancel button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void CancelButton_Click(object sender, EventArgs e)
{
this.ChangeMode(ProfilesMode.NONE);
}
/// <summary>
/// Called when the status list view selected index changes.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void StatusListViewSelectedIndexChanged(
object sender, EventArgs e)
{
updateButton.Enabled = statusListView.SelectedIndices.Count != 0;
}
/// <summary>
/// Called when the profiles combo box selected index changes.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void ProfilesComboBox_SelectedIndexChanged(
object sender,
EventArgs e)
{
if (profilesComboBox.SelectedIndex != -1)
{
this.ChangeMode(ProfilesMode.EDIT);
}
}
/// <summary>
/// Called when the auto detect IP address check box checked status
/// changes.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void AutoDetectCheckBox_CheckedChanged(
object sender,
EventArgs e)
{
ipAddressTextBox.Enabled = !autoDetectCheckBox.Checked;
if (autoDetectCheckBox.Checked)
{
ipAddressTextBox.Text = string.Empty;
}
}
/// <summary>
/// Called when the notify icon is double-clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void NotifyIcon_MouseDoubleClick(
object sender,
MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
/// <summary>
/// Called when the main form is resized.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
/// <summary>
/// Called when the main form is closing.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void MainForm_FormClosing(
object sender,
FormClosingEventArgs e)
{
this.SaveProfiles();
}
/// <summary>
/// Called when the Exit button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
/// <summary>
/// Links dynamic DNS profiles with entries in a combo box.
/// </summary>
private class ComboBoxItem
{
/// <summary>
/// Initializes a new instance of the <see cref="ComboBoxItem"/>
/// class.
/// </summary>
/// <param name="text">The text associated with the item.</param>
/// <param name="id">The ID associated with the item.</param>
public ComboBoxItem(string text, Guid id)
{
this.Text = text;
this.Id = id;
}
/// <summary>
/// Gets or sets the text associated with the item.
/// </summary>
public string Text
{
get;
set;
}
/// <summary>
/// Gets or sets ID associated with the item.
/// </summary>
public Guid Id
{
get;
set;
}
/// <summary>
/// Returns the text associated with the item.
/// </summary>
/// <returns>The text associated with the item.</returns>
public override string ToString()
{
return this.Text;
}
}
}
}