forked from sbozzie/test-intel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
650 lines (604 loc) · 25 KB
/
Copy pathMainForm.cs
File metadata and controls
650 lines (604 loc) · 25 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
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
using Microsoft.Win32;
using PleaseIgnore.IntelMap;
using System;
using System.ComponentModel;
using System.Security;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using System.Diagnostics;
using TestIntelReporter.Properties;
using System.Net;
using System.Security.Authentication;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
namespace TestIntelReporter {
public partial class MainForm : Form {
// Pen used for drawing the panel borders
private static readonly Pen borderPen = new Pen(Color.Gray, 4.0f);
// Time to show the channel list for if all green
private static readonly TimeSpan minimumChannelTime = new TimeSpan(0, 0, 30);
// The settings object
private readonly Settings settings;
// List of channel status flags
private readonly List<Label> channelFlags = new List<Label>();
// List of channel upload counts
private readonly List<Label> channelCounts = new List<Label>();
// Message we receive from Main() when another instance is run
private readonly uint wakeupMessage;
// Last time the "authentication invalid" balloon was shown
private DateTime? lastAuthBalloon;
// Number of times DaBigRedBoat has shown up in a message
private int noveltyCount;
// The most recently reported forum status
private IntelStatus oldStatus;
// The configuration is incomplete
private bool configError;
// The most recent update notification
private UpdateEventArgs updateEvent;
// Date and time the channel list was shown
private DateTime channelTime;
// Set true once we are shutting down
private bool shuttingDown;
/// <summary>
/// Initializes a new instance of the <see cref="MainForm"/> class.
/// </summary>
public MainForm() {
InitializeComponent();
// Register the 'wake up' message
try {
this.wakeupMessage = NativeMethods.RegisterWindowMessage(Program.mutexName);
} catch {
this.wakeupMessage = 0;
}
// Update some fields
this.Icon = Resources.AppIcon;
this.notifyIcon.Icon = Resources.AppIcon;
this.pictureBoxDino.Image = Resources.MiddleManagementDino;
labelAppName.Text = string.Format(
Application.CurrentCulture,
labelAppName.Text,
Application.ProductVersion);
// Finish initialization
this.settings = new Settings();
if (!String.IsNullOrEmpty(settings.Username)) {
intelReporter.Username = settings.Username;
} else {
this.configError = true;
}
if (!String.IsNullOrEmpty(settings.PasswordHash)) {
intelReporter.PasswordHash = settings.PasswordHash;
} else {
this.configError = true;
}
}
/// <summary>
/// Looking for the wake-up message.
/// </summary>
protected override void WndProc(ref Message m) {
if ((this.wakeupMessage != 0) && (this.wakeupMessage == m.Msg)
&& !this.shuttingDown) {
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.TopMost = true;
this.TopMost = false;
} else {
base.WndProc(ref m);
}
}
/// <summary>
/// Starts up the intel reporting component.
/// </summary>
protected override void OnShown(EventArgs e) {
ThreadPool.QueueUserWorkItem((state) => this.intelReporter.Start());
this.updateCheck.Start();
this.UpdateStatus();
base.OnShown(e);
}
/// <summary>
/// Recenter the panels when returning from minimization.
/// </summary>
protected override void OnResize(EventArgs e) {
if (this.WindowState != FormWindowState.Minimized) {
this.CenterPanel(this.panelAuthentication);
this.CenterPanel(this.panelAuthError);
this.CenterPanel(this.panelChannels);
this.CenterPanel(this.panelStatus);
} else {
this.Visible = false;
}
base.OnResize(e);
}
/// <summary>
/// Hide the window while we are disposing of the session.
/// </summary>
protected override void OnClosing(CancelEventArgs e) {
base.OnClosing(e);
if (!e.Cancel) {
this.shuttingDown = true;
this.Visible = false;
this.notifyIcon.Visible = false;
}
}
/// <summary>
/// Actives the specified pseudo-dialog within the parent window.
/// The operation includes centering, z-order manipulation, and
/// focus changes.
/// </summary>
private void ShowPanel(Control panel, Control focus) {
// Recenter and show a child panel
this.CenterPanel(panel);
panel.BringToFront();
panel.Visible = true;
(focus ?? panel).Focus();
}
/// <summary>
/// Recenter a pseudo-dialog within the window.
/// </summary>
private void CenterPanel(Control panel) {
var margin = this.ClientSize - panel.Size;
margin.Height /= 2;
margin.Width /= 2;
panel.Location = this.ClientRectangle.Location + margin;
}
/// <summary>
/// Draws a border for the pseudo-dialogs.
/// </summary>
private void DrawBorder(object sender, PaintEventArgs e) {
var panel = (Control)sender;
var rect = panel.ClientRectangle;
e.Graphics.DrawRectangle(borderPen,
rect.Left + 0.5f * borderPen.Width,
rect.Top + 0.5f * borderPen.Width,
rect.Width - borderPen.Width,
rect.Height - borderPen.Width);
}
#region Status Reporting
/// <summary>
/// Displays the status pseudo-dialog.
/// </summary>
private void ShowStatus(string title, string message) {
if (!panelAuthentication.Visible) {
this.AcceptButton = null;
panelAuthError.Visible = false;
panelChannels.Visible = false;
panelUpdate.Visible = false;
labelStatusTitle.Text = title;
labelStatus.Text = message;
this.ShowPanel(this.panelStatus, null);
}
}
/// <summary>
/// Displays the channel list pseudo-dialog.
/// </summary>
private void ShowChannelList() {
if (!panelAuthentication.Visible) {
panelStatus.Visible = false;
panelAuthError.Visible = false;
if (this.updateEvent != null) {
// Prioritize the update panel over the channel list
this.panelChannels.Visible = false;
this.ShowPanel(this.panelUpdate, this.buttonUpdate);
this.AcceptButton = this.buttonUpdate;
} else if (this.oldStatus != IntelStatus.Active) {
// Channel list being shown for the first time
this.channelTime = DateTime.UtcNow;
this.timerChannels.Enabled = true;
this.AcceptButton = null;
this.ShowPanel(this.panelChannels, null);
} else {
// Make sure channel list is always centered
this.CenterPanel(this.panelChannels);
}
}
}
/// <summary>
/// Performs an UI manipulations required for GUI depicted status.
/// </summary>
private void UpdateStatus() {
// Simple updates
labelCounts.Text = String.Join(
Resources.Stats_Join,
FormatCount(
intelReporter.IntelSent,
Resources.IntelCount_Zero,
Resources.IntelCount_One,
Resources.IntelCount_Many),
FormatCount(
intelReporter.IntelDropped,
Resources.DropCount_Zero,
Resources.DropCount_One,
Resources.DropCount_Many),
FormatCount(
intelReporter.Users,
Resources.UserCount_Zero,
Resources.UserCount_One,
Resources.UserCount_Many),
FormatCount(
this.noveltyCount,
Resources.NoveltyCount_Zero,
Resources.NoveltyCount_One,
Resources.NoveltyCount_Many)
);
// Authentication errors are handled specially
if (this.configError && !panelAuthentication.Visible) {
this.ShowAuthWindow();
}
// Update the status string
var status = intelReporter.Status;
var statusString = Resources.ResourceManager.GetString(
String.Format(
CultureInfo.InvariantCulture,
"StatusString_{0}", status))
?? Resources.StatusString_Unknown;
this.labelStatusString.Text = String.Format(
CultureInfo.CurrentCulture,
statusString,
status,
intelReporter.Path);
// Status changes
switch (status) {
case IntelStatus.Starting:
// Starting up...
break;
case IntelStatus.Active:
// Normal operation
this.ShowChannelList();
if (this.updateEvent != null) {
this.notifyIcon.Text = Resources.NotifyIcon_Upgrade;
} else {
this.notifyIcon.Text = Resources.NotifyIcon_Active;
}
break;
case IntelStatus.Waiting:
// Normal operation
if (this.updateEvent != null) {
this.ShowChannelList();
this.notifyIcon.Text = Resources.NotifyIcon_Upgrade;
} else {
this.ShowStatus(
Resources.IntelStatus_IdleTitle,
Resources.IntelStatus_Idle);
this.notifyIcon.Text = Resources.NotifyIcon_Inactive;
}
break;
case IntelStatus.AuthenticationError:
// Doesn't like our password
if (!this.configError) {
this.ShowAuthError(
Resources.IntelStatus_AuthTitle,
Resources.IntelStatus_Auth);
}
if (!this.lastAuthBalloon.HasValue
|| (this.lastAuthBalloon + new TimeSpan(TimeSpan.TicksPerDay) < DateTime.Now)) {
this.notifyIcon.ShowBalloonTip(10000,
Resources.Auth_NotificationTitle,
Resources.Auth_NotificationText,
ToolTipIcon.Error);
this.lastAuthBalloon = DateTime.Now;
}
this.notifyIcon.Text = Resources.NotifyIcon_AuthError;
break;
case IntelStatus.InvalidPath:
// Couldn't find the log directory
this.ShowStatus(
Resources.IntelStatus_MissingTitle,
Resources.IntelStatus_Missing);
this.notifyIcon.Text = Resources.NotifyIcon_Error;
break;
case IntelStatus.NetworkError:
// Unable to contact the network server
this.ShowStatus(
Resources.IntelStatus_ErrorTitle,
Resources.IntelStatus_Error);
this.notifyIcon.Text = Resources.NotifyIcon_Error;
break;
default:
// This represents a pretty critical failure of the
// system, so it gets priority over everything, including
// user entry.
panelAuthentication.Visible = false;
this.ShowStatus(
Resources.IntelStatus_FatalTitle,
Resources.IntelStatus_Fatal);
this.notifyIcon.Text = Resources.NotifyIcon_Error;
break;
}
this.oldStatus = status;
}
/// <summary>
/// Sent by <see cref="IntelReporter"/> every time it parses a
/// new log entry.
/// </summary>
private void intelReporter_IntelReported(object sender, IntelEventArgs e) {
messageView.PushMessage(e);
if (e.Message.IndexOf("Dabigredboat", StringComparison.OrdinalIgnoreCase) != -1) {
++this.noveltyCount;
this.UpdateStatus();
}
}
/// <summary>
/// Sent by <see cref="IntelReporter"/> whenever there is some
/// sort of status change.
/// </summary>
private void intelReporter_PropertyChanged(object sender, PropertyChangedEventArgs e) {
// Make sure we aren't disposed/in the process of disposing
if (this.Disposing || this.InvokeRequired) {
return;
}
// Pass up the chain
this.UpdateStatus();
// Update the channel list
if (String.IsNullOrEmpty(e.PropertyName) || (e.PropertyName == "Channels")) {
var visible = panelChannels.Visible;
// Clear out the old channel list
foreach (var label in panelChannels.Controls
.OfType<Label>()
.Where(x => x.Tag != null)
.ToArray()) {
panelChannels.Controls.Remove(label);
label.Dispose();
}
channelFlags.Clear();
channelCounts.Clear();
// Clear out the old rows
while(panelChannels.RowStyles.Count > 1) {
panelChannels.RowStyles.RemoveAt(1);
}
// Create a new channel list
foreach (var channel in intelReporter.Channels
.OrderBy(x => x.Name)) {
var row = panelChannels.RowStyles.Count;
panelChannels.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var status = new Label {
Tag = channel,
ImageList = this.imageList,
Padding = new Padding(0)
};
panelChannels.Controls.Add(status, 0, row);
channelFlags.Add(status);
var name = new Label {
Text = channel.Name,
Tag = channel,
Padding = new Padding(0),
Anchor = AnchorStyles.Left | AnchorStyles.Right
};
panelChannels.Controls.Add(name, 1, row);
var count = new Label {
Text = String.Empty,
Tag = channel,
Padding = new Padding(0),
TextAlign = ContentAlignment.MiddleRight,
Anchor = AnchorStyles.Left | AnchorStyles.Right
};
panelChannels.Controls.Add(count, 2, row);
channelCounts.Add(count);
}
if (visible) {
// Will recenter the channel list
this.ShowPanel(this.panelChannels, null);
}
}
// Update the channel statistics
foreach (var flag in channelFlags) {
var channel = (IntelChannel)flag.Tag;
var logFile = channel.LogFile;
if (logFile != null) {
flag.ImageIndex = 0;
} else {
flag.ImageIndex = 1;
}
}
foreach (var label in channelCounts) {
var channel = (IntelChannel)label.Tag;
var count = channel.IntelCount;
label.Text = FormatCount(
channel.IntelCount,
String.Empty,
Resources.IntelCount_One,
Resources.IntelCount_Many);
}
}
/// <summary>
/// Formats an integer count using seperate strings for
/// zero, one, or many countable items.
/// </summary>
private static string FormatCount(int count, string formatZero,
string formatOne, string formatMany) {
if (count <= 0) {
return String.Format(
Application.CurrentCulture,
formatZero,
count);
} else if (count == 1) {
return String.Format(
Application.CurrentCulture,
formatOne,
count);
} else {
return String.Format(
Application.CurrentCulture,
formatMany,
count);
}
}
/// <summary>
/// Hides the channel list if all the channels are active.
/// </summary>
private void timerChannels_Tick(object sender, EventArgs e) {
switch (this.oldStatus) {
case IntelStatus.Active:
if (this.updateEvent == null) {
// Hide the channel list if everything's green
if (this.intelReporter.Channels
.Any(x => x.Status != IntelStatus.Active)) {
this.channelTime = DateTime.UtcNow;
this.ShowPanel(this.panelChannels, null);
} else if ((this.channelTime + minimumChannelTime) < DateTime.UtcNow) {
this.panelChannels.Visible = false;
}
} else {
// Always going to show the update dialog
this.timerChannels.Enabled = false;
}
break;
default:
// No need to continue watching the channel list
this.timerChannels.Enabled = false;
break;
}
}
#endregion
#region Authentication Handling
/// <summary>
/// Displays the authentication error dialog (includes a button).
/// </summary>
private void ShowAuthError(string title, string message) {
panelStatus.Visible = false;
panelAuthError.Visible = false;
panelChannels.Visible = false;
panelUpdate.Visible = false;
labelAuthErrorTitle.Text = title;
labelAuthError.Text = message;
this.ShowPanel(this.panelAuthError, this.buttonChangeAuth);
this.AcceptButton = this.buttonChangeAuth;
}
/// <summary>
/// Displays the login window.
/// </summary>
private void ShowAuthWindow() {
panelStatus.Visible = false;
panelAuthError.Visible = false;
panelChannels.Visible = false;
panelUpdate.Visible = false;
textBoxUsername.Text = intelReporter.Username;
textBoxPassword.Text = String.Empty;
this.textBoxAuth_TextChanged(null, EventArgs.Empty);
ShowPanel(this.panelAuthentication, this.textBoxUsername);
this.AcceptButton = this.buttonLogin;
}
/// <summary>
/// Reevaluate the validity of the authentication inputs and
/// adjust the controls to reflect that.
/// </summary>
private void textBoxAuth_TextChanged(object sender, EventArgs e) {
bool authValid = true;
if (!String.IsNullOrWhiteSpace(textBoxUsername.Text)) {
textBoxUsername.BackColor = Color.White;
} else {
textBoxUsername.BackColor = Color.Pink;
authValid = false;
}
if (!String.IsNullOrWhiteSpace(textBoxPassword.Text)) {
textBoxPassword.BackColor = Color.White;
} else {
textBoxPassword.BackColor = Color.Pink;
authValid = false;
}
buttonLogin.Enabled = authValid;
}
/// <summary>
/// Login button has been clicked. Begin an authentication
/// attempt.
/// </summary>
private void buttonLogin_Click(object sender, EventArgs e) {
// TODO: Show some sort of status dialog
textBoxUsername.Enabled = false;
textBoxPassword.Enabled = false;
buttonLogin.Enabled = false;
var username = textBoxUsername.Text.Trim();
var password = textBoxPassword.Text.Trim();
ThreadPool.QueueUserWorkItem((state) => {
try {
intelReporter.Authenticate(username, password);
this.BeginInvoke(new Action(() => {
this.panelAuthentication.Visible = false;
this.configError = false;
this.settings.Username = intelReporter.Username;
this.settings.PasswordHash = intelReporter.PasswordHash;
this.settings.Save();
}));
} catch (WebException) {
this.BeginInvoke(new Action(() => {
this.ShowAuthError(
Resources.IntelStatus_ErrorTitle,
Resources.Authenticate_Network);
}));
} catch (AuthenticationException) {
this.BeginInvoke(new Action(() => {
this.ShowAuthError(
Resources.IntelStatus_AuthTitle,
Resources.Authenticate_Auth);
}));
} catch {
this.BeginInvoke(new Action(() => {
panelAuthentication.Visible = false;
this.ShowStatus(
Resources.IntelStatus_FatalTitle,
Resources.IntelStatus_Fatal);
}));
}
});
}
/// <summary>
/// Clicked da butan in an authentication error dialog.
/// </summary>
private void buttonChangeAuth_Click(object sender, EventArgs e) {
if (panelAuthentication.Visible) {
// Maintain the current login
panelAuthError.Visible = false;
textBoxUsername.Enabled = true;
textBoxPassword.Enabled = true;
this.AcceptButton = this.buttonLogin;
} else {
// Open a new login window
this.ShowAuthWindow();
}
}
#endregion
#region Update Checking
/// <summary>
/// Raised by <see cref="updateCheck"/> when a new version has been
/// made available.
/// </summary>
private void updateCheck_UpdateAvailable(object sender, UpdateEventArgs e) {
this.updateEvent = e;
this.buttonUpdate.Enabled = (e.UpdateUri != null)
&& e.UpdateUri.StartsWith("http");
this.labelUpdateTitle.Text = Resources.IntelStatus_VersionTitle;
this.labelUpdate.Text = String.Format(
CultureInfo.CurrentCulture,
Resources.IntelStatus_Version,
e.OldVersion,
e.NewVersion,
e.UpdateUri);
this.UpdateStatus();
this.notifyIcon.ShowBalloonTip(10000,
Resources.Update_NotificationTitle,
Resources.Update_NotificationText,
ToolTipIcon.Info);
}
/// <summary>
/// User has requested we go to the update website.
/// </summary>
private void buttonUpdate_Click(object sender, EventArgs e) {
Process.Start(this.updateEvent.UpdateUri);
}
#endregion
#region Notify Icon
private void notifyIcon_BalloonTipClicked(object sender, EventArgs e) {
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.TopMost = true;
this.TopMost = false;
}
private void notifyIcon_DoubleClick(object sender, EventArgs e) {
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.TopMost = true;
this.TopMost = false;
}
#endregion
}
}