-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathNetCheck.cs
More file actions
2048 lines (1930 loc) · 121 KB
/
Copy pathNetCheck.cs
File metadata and controls
2048 lines (1930 loc) · 121 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
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
[assembly: AssemblyTitle("NetCheckMonitor")]
[assembly: AssemblyProduct("NetCheckMonitor")]
[assembly: AssemblyDescription("Internet connection monitoring and outage reporting")]
[assembly: AssemblyCompany("廖阿輝")]
[assembly: AssemblyVersion("0.9.15.0")]
[assembly: AssemblyFileVersion("0.9.15.0")]
namespace NetCheck
{
internal static class SingleInstance
{
private const string DefaultMutexName = @"Local\NetCheckMonitor-7C54A9D1-839F-4D9A-A803-EC852DA27A14";
private const string ShowMessageName = "NetCheckMonitor.ShowExistingWindow.7C54A9D1-839F-4D9A-A803-EC852DA27A14";
internal static readonly int ShowWindowMessage = (int)RegisterWindowMessage(ShowMessageName);
private static readonly IntPtr HwndBroadcast = new IntPtr(0xFFFF);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern uint RegisterWindowMessage(string messageName);
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr window, int message, IntPtr wParam, IntPtr lParam);
internal static bool TryAcquire(out Mutex mutex)
{
bool createdNew;
string name = Environment.GetEnvironmentVariable("NETCHECK_INSTANCE_NAME");
if (String.IsNullOrWhiteSpace(name)) name = DefaultMutexName;
mutex = new Mutex(true, name, out createdNew);
if (createdNew) return true;
mutex.Dispose();
mutex = null;
return false;
}
internal static void ShowExistingWindow()
{
if (ShowWindowMessage == 0) return;
for (int i = 0; i < 6; i++)
{
PostMessage(HwndBroadcast, ShowWindowMessage, IntPtr.Zero, IntPtr.Zero);
Thread.Sleep(120);
}
}
}
internal enum TrayConnectionState
{
Idle,
Checking,
Online,
Offline,
Paused
}
internal sealed class CheckRecord
{
public DateTime Time;
public bool Online;
public long LatencyMs;
public string Target;
public string Detail;
public string Status;
public bool JustConfirmed;
public bool JustRecovered;
public int RetryNumber;
public DateTime OutageStart;
public NetworkSnapshot Network;
public AdvancedDiagnosticResult Diagnostic;
}
internal sealed class TimePeriod
{
public DateTime Start;
public DateTime End;
}
internal sealed class MainForm : Form
{
private readonly Label stateLabel = new Label();
private readonly Label lastLabel = new Label();
private readonly Label statsLabel = new Label();
private readonly Label networkInfoLabel = new Label();
private readonly Button startButton = new Button();
private readonly Button pauseButton = new Button();
private readonly Button reportButton = new Button();
private readonly Button dataButton = new Button();
private readonly Button exitButton = new Button();
private readonly Button aboutButton = new Button();
private readonly Button settingsButton = new Button();
private readonly Button eventNoteButton = new Button();
private readonly Label versionLabel = new Label();
private readonly NumericUpDown intervalBox = new NumericUpDown();
private readonly ListView recentList = new ListView();
private readonly NotifyIcon trayIcon = new NotifyIcon();
private Icon neutralTrayIcon;
private Icon checkingTrayIcon;
private Icon onlineTrayIcon;
private Icon offlineTrayIcon;
private System.Threading.Timer timer;
private System.Threading.Timer speedScheduleTimer;
private StreamWriter writer;
private StreamWriter backupWriter;
private string csvPath;
private string backupCsvPath;
private string reportPath;
private string machineName;
private string machineId;
private string machineIdSource;
private string sessionFileStem;
private DateTime sessionStart;
private DateTime pauseStart;
private bool running;
private bool paused;
private bool allowExit;
private string exitSaveError;
private int checking;
private DateTime lastAutoReport = DateTime.MinValue;
private string logWarning;
private int consecutiveFailures;
private int checkIntervalSeconds = 60;
private bool outageConfirmed;
private DateTime suspectedStart;
private DateTime lastStateHeartbeat;
private DateTime processStartedUtc = Process.GetCurrentProcess().StartTime.ToUniversalTime();
private CloudBackupManager cloudManager;
private GmailNotificationManager gmailManager;
private MonitorTargetSettings monitorSettings;
private NetworkSnapshot currentNetwork;
private AdvancedDiagnosticResult lastAdvancedDiagnostic;
private DateTime lastAdvancedDiagnosticAt = DateTime.MinValue;
private bool shutdownBlockReasonActive;
private int speedTestRunning;
private SpeedTestCancellation speedCancellation;
private System.Windows.Forms.Timer updateWaitTimer;
private UpdatePackage pendingUpdate;
private DateTime updateWaitDeadline;
private bool updateWasMonitoring;
private readonly List<CheckRecord> records = new List<CheckRecord>();
private readonly List<TimePeriod> pauses = new List<TimePeriod>();
private readonly List<EventNote> eventNotes = new List<EventNote>();
private const int FastRetrySeconds = 5;
private const int FastRetryLimit = 6;
private const int OutageBackoffSeconds = 30;
private static readonly string[] TestUrls = new string[] {
"https://www.msftconnecttest.com/connecttest.txt",
"https://connectivitycheck.gstatic.com/generate_204",
"https://cp.cloudflare.com/generate_204"
};
private string[] activeTestUrls = (string[])TestUrls.Clone();
[DllImport("kernel32.dll")]
private static extern uint SetThreadExecutionState(uint esFlags);
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool ShutdownBlockReasonCreate(IntPtr window, string reason);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool ShutdownBlockReasonDestroy(IntPtr window);
private const uint ES_CONTINUOUS = 0x80000000;
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
private const int WM_QUERYENDSESSION = 0x0011;
public MainForm()
{
Text = L.T("對外網路連線能力監控程式", "NetCheckMonitor Network Monitor");
Icon = LoadApplicationIcon();
Font = new Font("Microsoft JhengHei UI", 10F);
ClientSize = new Size(780, 570);
MinimumSize = new Size(700, 520);
StartPosition = FormStartPosition.CenterScreen;
var title = new Label { Text = L.T("對外連線能力監控", "Network Connection Monitor"), Font = new Font(Font.FontFamily, 18F, FontStyle.Bold), AutoSize = true, Location = new Point(22, 18) };
versionLabel.Text = "v" + AboutForm.AppVersion;
versionLabel.Font = new Font(Font.FontFamily, 8F);
versionLabel.ForeColor = Color.DarkGray;
versionLabel.AutoSize = true;
versionLabel.Location = new Point(title.Left + TextRenderer.MeasureText(title.Text, title.Font).Width + 8, 34);
stateLabel.Text = L.T("尚未開始", "Not started");
stateLabel.Font = new Font(Font.FontFamily, 16F, FontStyle.Bold);
stateLabel.ForeColor = Color.DimGray;
stateLabel.AutoSize = true;
stateLabel.Location = new Point(25, 62);
var intervalLabel = new Label { Text = L.T("檢查間隔(秒)", "Interval (seconds)"), AutoSize = true, Location = new Point(535, 25) };
intervalBox.Minimum = 10;
intervalBox.Maximum = 3600;
intervalBox.Value = 60;
intervalBox.Location = new Point(660, 21);
intervalBox.Size = new Size(90, 25);
pauseButton.Text = L.T("暫停", "Pause");
reportButton.Text = L.T("查看報表", "View Report");
dataButton.Text = L.T("下載報表 PDF 文件", "Download PDF Report");
exitButton.Text = L.T("關閉程式並停止監控", "Exit and Stop Monitoring");
aboutButton.Text = L.T("關於", "About");
settingsButton.Text = L.T("設定", "Settings");
eventNoteButton.Text = L.T("事件註記", "Event Note");
startButton.SetBounds(25, 112, 145, 38);
startButton.Font = new Font(Font.FontFamily, 10F, FontStyle.Bold);
UpdateStartButton(false);
pauseButton.SetBounds(180, 112, 95, 38);
eventNoteButton.SetBounds(285, 112, 110, 38);
reportButton.SetBounds(405, 112, 120, 38);
dataButton.SetBounds(535, 112, 220, 38);
exitButton.SetBounds(565, 542, 190, 24);
exitButton.Font = new Font(Font.FontFamily, 8.5F, FontStyle.Bold);
exitButton.ForeColor = Color.Firebrick;
exitButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
settingsButton.SetBounds(25, 542, 90, 24);
settingsButton.Font = new Font(Font.FontFamily, 8.5F);
settingsButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
aboutButton.SetBounds(125, 542, 70, 24);
aboutButton.Font = new Font(Font.FontFamily, 8.5F);
aboutButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
eventNoteButton.Enabled = false;
pauseButton.Enabled = false;
reportButton.Enabled = false;
lastLabel.Text = L.T("最後檢查:—", "Last check: —");
lastLabel.AutoSize = true;
lastLabel.Location = new Point(27, 167);
statsLabel.Text = L.T("有效檢查 0 次|正常 0 次|斷線 0 次|暫停時間不列入統計", "Checks 0 | Online 0 | Offline 0 | Paused time excluded");
statsLabel.AutoSize = true;
statsLabel.Location = new Point(27, 194);
networkInfoLabel.Text = L.T("目前網卡:正在讀取…", "Adapter: Reading…");
networkInfoLabel.AutoEllipsis = true;
networkInfoLabel.ForeColor = Color.DimGray;
networkInfoLabel.Font = new Font(Font.FontFamily, 8.5F);
networkInfoLabel.SetBounds(27, 217, 728, 24);
recentList.Location = new Point(25, 249);
recentList.Size = new Size(730, 289);
recentList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
recentList.View = View.Details;
recentList.FullRowSelect = true;
recentList.GridLines = true;
recentList.Columns.Add(L.T("時間", "Time"), 155);
recentList.Columns.Add(L.T("狀態", "Status"), 90);
recentList.Columns.Add(L.T("延遲", "Latency"), 90);
recentList.Columns.Add(L.T("檢測目標 / 說明", "Target / Details"), 365);
Controls.AddRange(new Control[] { title, versionLabel, stateLabel, intervalLabel, intervalBox, startButton, pauseButton, reportButton, dataButton, lastLabel, statsLabel, networkInfoLabel, recentList, exitButton, aboutButton, settingsButton, eventNoteButton });
startButton.Click += delegate { if (!running) StartMonitoring(); };
pauseButton.Click += delegate { TogglePause(); };
reportButton.Click += delegate { if (running) CreateLiveReport(true); else OpenReport(); };
dataButton.Click += delegate { ShowDataManager(); };
exitButton.Click += delegate { RequestExit(); };
aboutButton.Click += delegate { using (var form = new AboutForm(BeginOnlineUpdate)) form.ShowDialog(this); };
settingsButton.Click += delegate { ShowMonitorSettings(); };
eventNoteButton.Click += delegate { ShowEventNoteDialog(); };
FormClosing += OnFormClosing;
Shown += delegate { BeginInvoke((MethodInvoker)HandleStartupMonitoring); };
Resize += delegate { if (WindowState == FormWindowState.Minimized) HideToTray(); };
neutralTrayIcon = (Icon)this.Icon.Clone();
checkingTrayIcon = CreateStatusIcon(Color.DarkOrange);
onlineTrayIcon = CreateStatusIcon(Color.LimeGreen);
offlineTrayIcon = CreateStatusIcon(Color.Red);
trayIcon.Text = L.T("對外網路連線能力監控程式", "NetCheckMonitor Network Monitor");
trayIcon.Icon = neutralTrayIcon;
trayIcon.Visible = false;
trayIcon.DoubleClick += delegate { ShowFromTray(); };
var trayMenu = new ContextMenuStrip();
trayMenu.Items.Add(L.T("顯示視窗", "Show Window"), null, delegate { ShowFromTray(); });
trayMenu.Items.Add(L.T("結束程式", "Exit"), null, delegate { ShowFromTray(); RequestExit(); });
trayIcon.ContextMenuStrip = trayMenu;
EnsureMachineIdentity();
try { reportPath = ArchiveReport.EnsureCumulativeHtml(machineName, machineId); }
catch { reportPath = ArchiveReport.FindLatestCumulativeHtml(machineId); }
reportButton.Enabled = !String.IsNullOrEmpty(reportPath);
monitorSettings = MonitorSettingsStore.Load();
if (String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("NETCHECK_MONITOR_SETTINGS")))
try { AutoStartManager.SetEnabled(monitorSettings.AutoStartWindows); } catch { }
cloudManager = new CloudBackupManager(machineName, machineId);
gmailManager = new GmailNotificationManager(machineName, machineId);
}
private void StartMonitoring()
{
records.Clear();
pauses.Clear();
eventNotes.Clear();
recentList.Items.Clear();
reportPath = null;
reportButton.Text = L.T("查看報表", "View Report");
reportButton.Enabled = true;
lastAutoReport = DateTime.MinValue;
logWarning = null;
ResetOutageTracking();
sessionStart = DateTime.Now;
checkIntervalSeconds = (int)intervalBox.Value;
EnsureMachineIdentity();
monitorSettings = MonitorSettingsStore.Load();
activeTestUrls = MonitorSettingsStore.GetEffectiveTargets(monitorSettings, TestUrls);
currentNetwork = NetworkStatusReader.Capture();
string baseSessionFileStem = "NetCheck_" + SafeFilePart(machineName, 16) + "-" + machineId + "_" + sessionStart.ToString("yyyyMMdd_HHmmss");
string executableDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string dataDir = Path.Combine(executableDir, "NetCheck_Data");
try { Directory.CreateDirectory(dataDir); }
catch { dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "NetCheck_Data"); Directory.CreateDirectory(dataDir); }
sessionFileStem = AllocateSessionFileStem(dataDir, baseSessionFileStem);
csvPath = Path.Combine(dataDir, sessionFileStem + ".csv");
try { writer = CreateDurableWriter(csvPath); }
catch
{
dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NetCheck", "Data");
Directory.CreateDirectory(dataDir);
sessionFileStem = AllocateSessionFileStem(dataDir, baseSessionFileStem);
csvPath = Path.Combine(dataDir, sessionFileStem + ".csv");
writer = CreateDurableWriter(csvPath);
}
try
{
string backupDir = Environment.GetEnvironmentVariable("NETCHECK_BACKUP_DIR");
if (String.IsNullOrEmpty(backupDir)) backupDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NetCheck", "Recovery");
Directory.CreateDirectory(backupDir);
backupCsvPath = Path.Combine(backupDir, Path.GetFileName(csvPath));
if (!String.Equals(Path.GetFullPath(backupCsvPath), Path.GetFullPath(csvPath), StringComparison.OrdinalIgnoreCase)) backupWriter = CreateDurableWriter(backupCsvPath);
}
catch { backupWriter = null; backupCsvPath = null; }
WriteLogLine("Timestamp,Type,Status,LatencyMs,Target,Detail");
WriteMarker("COMPUTER", machineName + " [" + machineId + "]" + L.T(";識別方式:", "; identity: ") + machineIdSource);
WriteMarker("STARTED", L.T("開始監控;檢查間隔 ", "Monitoring started; interval ") + intervalBox.Value + L.T(" 秒", " seconds"));
WriteMarker("TARGETS", (monitorSettings.UseCustomTargets ? L.T("自訂目標:", "Custom targets: ") : L.T("內建目標:", "Built-in targets: ")) + String.Join(" | ", activeTestUrls));
WriteMarker("ADVANCED_DIAGNOSTICS", monitorSettings.AdvancedDiagnosticsEnabled ? "ENABLED" : "DISABLED");
WriteMarker("POWER_PROTECTION", PowerProtectionMarker(monitorSettings));
WriteMarker("NETWORK", currentNetwork.ToMarker());
running = true;
paused = false;
intervalBox.Enabled = false;
UpdateStartButton(true);
settingsButton.Enabled = true;
pauseButton.Enabled = true;
eventNoteButton.Enabled = true;
pauseButton.Text = L.T("暫停", "Pause");
UpdatePowerProtection();
UpdateState(L.T("準備檢查…", "Preparing check…"), Color.DarkOrange);
RenderNetworkInfo(currentNetwork);
SetTrayConnectionState(TrayConnectionState.Checking, true);
PersistSessionState();
timer = new System.Threading.Timer(delegate { PerformCheck(); }, null, 0, Timeout.Infinite);
RefreshSpeedSchedule();
}
private void EnsureMachineIdentity()
{
if (!String.IsNullOrEmpty(machineId)) return;
machineName = Environment.MachineName;
machineId = GetMachineId(out machineIdSource);
}
private void ShowDataManager()
{
EnsureMachineIdentity();
using (var form = new DataReportForm(machineName, machineId)) form.ShowDialog(this);
}
private void BeginScheduledSpeedTest()
{
if (Interlocked.CompareExchange(ref speedTestRunning, 1, 0) != 0) return;
monitorSettings = monitorSettings ?? MonitorSettingsStore.Load();
SpeedTestOptions options = monitorSettings.SpeedTest ?? SpeedTestOptions.Defaults();
SpeedTestLevel level = options.EffectiveLevel;
if (!running || paused || !options.ScheduledEnabled) { Interlocked.Exchange(ref speedTestRunning, 0); RefreshSpeedSchedule(); return; }
DateTime blockedUntilUtc = GetSpeedTestBlockedUntilUtc(options);
if (blockedUntilUtc > DateTime.UtcNow)
{
Interlocked.Exchange(ref speedTestRunning, 0);
RefreshSpeedSchedule();
return;
}
NetworkCostState cost = NetworkCostReader.GetCurrent();
if (cost == NetworkCostState.Metered || cost == NetworkCostState.Roaming || cost == NetworkCostState.OverLimit)
{
if (!options.AllowMeteredNetwork)
{
var skipped = new SpeedTestResult { Time = DateTime.Now, Status = "SKIPPED", Level = level, Scheduled = true, Error = L.T("偵測到計量付費、漫遊或超過流量上限的網路,依設定略過。", "A metered, roaming, or over-limit connection was detected and skipped by configuration."), Network = NetworkStatusReader.Capture() };
try { SpeedTestStorage.Append(machineName, machineId, skipped); } catch { }
FinishSpeedTest(skipped); return;
}
if (MessageBox.Show(L.T("Windows 顯示目前可能是計量付費、漫遊或已超過流量上限的網路。測速可能產生額外費用,仍要繼續嗎?", "Windows reports a metered, roaming, or over-limit connection. The speed test may cause extra charges. Continue anyway?"), L.T("計量網路警告(1/2)", "Metered Network Warning (1/2)"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) { Interlocked.Exchange(ref speedTestRunning, 0); RefreshSpeedSchedule(); return; }
if (MessageBox.Show(L.T("再次確認:本次測速會立即下載及上傳大量資料,確定由您承擔可能的流量費用並開始嗎?", "Confirm again: this test immediately downloads and uploads substantial data. Do you accept possible data charges and want to start?"), L.T("計量網路最後確認(2/2)", "Final Metered Network Confirmation (2/2)"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) { Interlocked.Exchange(ref speedTestRunning, 0); RefreshSpeedSchedule(); return; }
}
options.LastAttemptUtc = DateTime.UtcNow;
monitorSettings.SpeedTest = options;
try { MonitorSettingsStore.Save(monitorSettings); } catch { }
speedCancellation = new SpeedTestCancellation();
ThreadPool.QueueUserWorkItem(delegate
{
SpeedTestResult result = CloudflareSpeedTest.Run(level, true, speedCancellation);
try { SpeedTestStorage.Append(machineName, machineId, result); }
catch (Exception ex) { result.Status = "FAILED"; result.Error = L.T("測速完成但無法儲存:", "Test completed but could not be saved: ") + ex.Message; }
if (!IsDisposed && IsHandleCreated) BeginInvoke((MethodInvoker)delegate { FinishSpeedTest(result); });
else Interlocked.Exchange(ref speedTestRunning, 0);
});
}
private void CancelSpeedTest()
{
SpeedTestCancellation value = speedCancellation;
if (value != null) value.Cancel();
}
private void FinishSpeedTest(SpeedTestResult result)
{
monitorSettings = monitorSettings ?? MonitorSettingsStore.Load();
monitorSettings.SpeedTest = monitorSettings.SpeedTest ?? SpeedTestOptions.Defaults();
if (result.Scheduled)
{
monitorSettings.SpeedTest.LastScheduledRunUtc = DateTime.UtcNow;
}
if (result.RateLimited)
{
int backoff = Math.Max(1, Math.Min(5, monitorSettings.SpeedTest.RateLimitBackoffLevel + 1));
double minutes = 60 * Math.Pow(2, backoff - 1);
if (result.RetryAfterSeconds > 0) minutes = Math.Max(minutes, Math.Ceiling(result.RetryAfterSeconds / 60.0));
monitorSettings.SpeedTest.RateLimitBackoffLevel = backoff;
monitorSettings.SpeedTest.ServerCooldownUntilUtc = DateTime.UtcNow.AddMinutes(Math.Min(1440, minutes));
result.Error = (result.Error ?? "") + L.T(";遠端伺服器已拒絕過於頻繁的要求,程式將暫停測速至 ", "; the remote server rejected overly frequent requests. Speed tests are paused until ") + monitorSettings.SpeedTest.ServerCooldownUntilUtc.ToLocalTime().ToString("yyyy/MM/dd HH:mm:ss");
}
else if (result.Status == "COMPLETED")
{
monitorSettings.SpeedTest.RateLimitBackoffLevel = 0;
monitorSettings.SpeedTest.ServerCooldownUntilUtc = DateTime.MinValue;
}
try { MonitorSettingsStore.Save(monitorSettings); } catch { }
string status = result.Status == "COMPLETED" ? L.T("測速完成", "Speed test") : result.Status == "SKIPPED" ? L.T("略過測速", "Speed test skipped") : result.Status == "CANCELLED" ? L.T("取消測速", "Speed test cancelled") : L.T("測速失敗", "Speed test failed");
AddRecent(result.Time, status, result.Status == "COMPLETED" ? result.IdleLatencyMs.ToString("0.0") + " ms" : "—", result.DisplaySummary, result.Status == "COMPLETED" ? Color.SeaGreen : Color.Firebrick);
speedCancellation = null;
Interlocked.Exchange(ref speedTestRunning, 0);
RefreshSpeedSchedule();
}
private void OpenSpeedTrendReport()
{
EnsureMachineIdentity();
try { SpeedTrendReport.Open(machineName, machineId); }
catch (Exception ex) { MessageBox.Show(L.T("無法產生速度趨勢報表:", "Could not create the speed trend report: ") + ex.Message, L.T("速度趨勢報表", "Speed Trend Report"), MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
private void RefreshSpeedSchedule()
{
if (speedScheduleTimer != null) { speedScheduleTimer.Dispose(); speedScheduleTimer = null; }
SpeedTestOptions options = monitorSettings == null ? null : monitorSettings.SpeedTest;
if (!running || paused || options == null || !options.ScheduledEnabled || Volatile.Read(ref speedTestRunning) == 1) return;
TimeSpan interval = TimeSpan.FromHours(Math.Max(1, options.IntervalHours));
DateTime scheduledDueUtc = options.LastScheduledRunUtc == DateTime.MinValue ? DateTime.UtcNow.Add(interval) : options.LastScheduledRunUtc.Add(interval);
DateTime cooldownDueUtc = GetSpeedTestBlockedUntilUtc(options);
if (cooldownDueUtc > scheduledDueUtc) scheduledDueUtc = cooldownDueUtc;
TimeSpan due = scheduledDueUtc - DateTime.UtcNow;
if (due < TimeSpan.FromSeconds(30)) due = TimeSpan.FromSeconds(30);
if (due > TimeSpan.FromDays(20)) due = TimeSpan.FromDays(20);
speedScheduleTimer = new System.Threading.Timer(delegate
{
if (!IsDisposed && IsHandleCreated) try { BeginInvoke((MethodInvoker)delegate { BeginScheduledSpeedTest(); }); } catch { }
}, null, due, Timeout.InfiniteTimeSpan);
}
private static DateTime GetSpeedTestBlockedUntilUtc(SpeedTestOptions options)
{
if (options == null) return DateTime.MinValue;
DateTime nowUtc = DateTime.UtcNow;
DateTime attemptUtc = options.LastAttemptUtc == DateTime.MinValue ? DateTime.MinValue : options.LastAttemptUtc.ToUniversalTime();
if (attemptUtc > nowUtc) attemptUtc = nowUtc;
DateTime normalCooldown = attemptUtc == DateTime.MinValue ? DateTime.MinValue : attemptUtc.AddMinutes(15);
DateTime serverCooldown = options.ServerCooldownUntilUtc == DateTime.MinValue ? DateTime.MinValue : options.ServerCooldownUntilUtc.ToUniversalTime();
if (serverCooldown > nowUtc.AddHours(24)) serverCooldown = nowUtc.AddHours(24);
return normalCooldown > serverCooldown ? normalCooldown : serverCooldown;
}
private void ClearStoredData()
{
if (running || (cloudManager != null && cloudManager.BackupInProgress))
{
MessageBox.Show(L.T("目前正在監控或雲端備份,不能清除資料。請等待工作完成;若正在監控,請使用「關閉程式並停止監控」,重新開啟後再清除。", "Saved data cannot be cleared while monitoring or a cloud backup is in progress. Wait for the work to finish; if monitoring is active, use Exit and Stop Monitoring, reopen the app, and then clear the data."), L.T("無法清除", "Unable to Clear"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (MessageBox.Show(L.T("這會刪除 NetCheck 管理的所有 CSV、HTML、即時報表與本機備援資料。\n\n自行下載到其他資料夾的 PDF 不會被刪除。此動作無法復原,確定繼續嗎?", "This will delete all CSV, HTML, live-report, and local recovery files managed by NetCheck.\n\nPDF files downloaded to other folders will not be deleted. This cannot be undone. Continue?"), L.T("清除全部資料", "Clear All Data"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) return;
int deleted;
List<string> failures = ArchiveReport.ClearAllData(out deleted);
if (failures.Count == 0) SessionStateStore.Delete();
if (failures.Count > 0)
{
string prefix = deleted == 0 ? L.T("沒有清除任何資料。偵測到仍被使用或無法刪除的檔案。", "No data was cleared. Some files are in use or could not be deleted.") : L.T("已清除 ", "Cleared ") + deleted + L.T(" 個檔案,但下列檔案無法刪除。", " files, but the following files could not be deleted.");
MessageBox.Show(prefix + L.T("\n請先結束所有 NetCheck 監控程式後再試一次。\n\n", "\nClose all NetCheck monitoring programs and try again.\n\n") + String.Join("\n", failures.ToArray()), L.T("資料清除未完成", "Data Clearing Incomplete"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
reportPath = null;
reportButton.Text = L.T("查看報表", "View Report");
reportButton.Enabled = false;
MessageBox.Show(L.T("已清除 ", "Cleared ") + deleted + L.T(" 個 NetCheck 儲存檔案。", " NetCheck saved files."), L.T("清除完成", "Clearing Complete"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ShowCloudSettings()
{
using (var form = new CloudBackupForm(cloudManager)) form.ShowDialog(this);
}
private void ShowGmailSettings()
{
using (var form = new GmailNotificationForm(gmailManager)) form.ShowDialog(this);
}
private void ShowMonitorSettings()
{
using (var form = new MonitorSettingsForm(monitorSettings, ForceRebuildDailyDetailReports, OpenSpeedTrendReport, ShowCloudSettings, ShowGmailSettings, ClearStoredData))
{
if (form.ShowDialog(this) != DialogResult.OK) return;
try
{
string previousLanguage = LanguagePreferenceStore.Load() ?? LanguagePreferenceStore.English;
bool restarted = ApplyMonitorSettings(form.Result);
bool languageChanged = !String.Equals(previousLanguage, form.SelectedLanguage, StringComparison.OrdinalIgnoreCase);
LanguagePreferenceStore.Save(form.SelectedLanguage);
string autoStartWarning = null;
try { AutoStartManager.SetEnabled(form.Result.AutoStartWindows); }
catch (Exception ex) { autoStartWarning = ex.Message; }
string message = restarted
? L.T("設定已儲存。原監控資料與報表已安全保存,並已使用新目標重新開始監控。", "Settings saved. The previous monitoring data and report were saved safely, and monitoring restarted with the new targets.")
: L.T("設定已儲存;目前監控使用的目標沒有變更,因此不需要重新啟動監控。", "Settings saved. The targets used by the current monitoring session did not change, so monitoring was not restarted.");
if (languageChanged) message += L.T("\n\n介面語言將在下次啟動程式時套用。", "\n\nThe interface language will be applied the next time the app starts.");
if (!String.IsNullOrEmpty(autoStartWarning)) message += L.T("\n\n但無法更新 Windows 自動啟動設定:", "\n\nWindows startup could not be updated: ") + autoStartWarning;
MessageBox.Show(message, form.Text, MessageBoxButtons.OK, String.IsNullOrEmpty(autoStartWarning) ? MessageBoxIcon.Information : MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(L.T("無法儲存設定:", "Could not save settings: ") + ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ForceRebuildDailyDetailReports()
{
string output = reportPath;
if (String.IsNullOrEmpty(output)) output = ArchiveReport.EnsureCumulativeHtml(machineName, machineId);
if (String.IsNullOrEmpty(output)) throw new InvalidOperationException(L.T("目前沒有可製作報表的測試資料。", "There is currently no test data available for a report."));
reportPath = ArchiveReport.ForceRebuildDailyDetailReports(output, running);
reportButton.Text = L.T("查看報表", "View Report");
reportButton.Enabled = true;
}
private void ShowEventNoteDialog()
{
if (!running) return;
using (var form = new EventNoteForm())
if (form.ShowDialog(this) == DialogResult.OK) AddEventNote(form.NoteText);
}
private void AddEventNote(string text)
{
if (!running || String.IsNullOrWhiteSpace(text)) return;
string value = text.Trim();
if (value.Length > 500) value = value.Substring(0, 500);
var note = new EventNote { Time = DateTime.Now, Text = value };
lock (eventNotes) eventNotes.Add(note);
WriteMarkerAt(note.Time, "EVENT_NOTE", note.Text);
PersistSessionState();
AddRecent(note.Time, L.T("事件", "Event"), "—", note.Text, Color.MediumPurple);
}
private bool ApplyMonitorSettings(MonitorTargetSettings updated)
{
if (updated == null) throw new ArgumentNullException("updated");
bool restart = running && MonitoringTargetsChanged(monitorSettings, updated);
MonitorSettingsStore.Save(updated);
monitorSettings = updated;
UpdatePowerProtection();
RefreshSpeedSchedule();
if (!updated.AdvancedDiagnosticsEnabled) { lastAdvancedDiagnostic = null; lastAdvancedDiagnosticAt = DateTime.MinValue; }
if (running)
{
WriteMarker("ADVANCED_DIAGNOSTICS", updated.AdvancedDiagnosticsEnabled ? "ENABLED" : "DISABLED");
WriteMarker("POWER_PROTECTION", PowerProtectionMarker(updated));
}
if (restart)
{
StopMonitoring(false);
StartMonitoring();
}
return restart;
}
private static bool MonitoringTargetsChanged(MonitorTargetSettings before, MonitorTargetSettings after)
{
if (before == null || after == null) return true;
if (before.UseCustomTargets != after.UseCustomTargets) return true;
if (!before.UseCustomTargets) return false;
List<string> oldTargets = before.CustomTargets ?? new List<string>();
List<string> newTargets = after.CustomTargets ?? new List<string>();
if (oldTargets.Count != newTargets.Count) return true;
for (int i = 0; i < oldTargets.Count; i++)
if (!String.Equals(oldTargets[i], newTargets[i], StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private void TogglePause()
{
if (!running) return;
if (!paused)
{
paused = true;
pauseStart = DateTime.Now;
if (timer != null) timer.Change(Timeout.Infinite, Timeout.Infinite);
RefreshSpeedSchedule();
WriteMarker("PAUSED", L.T("監控暫停;此時段不列入統計", "Monitoring paused; this period is excluded from statistics"));
AddRecent(pauseStart, L.T("暫停", "Paused"), "—", L.T("此時段不列入統計", "This period is excluded from statistics"), Color.Gray);
pauseButton.Text = L.T("繼續", "Resume");
UpdateState(L.T("已暫停(不列入統計)", "Paused (excluded from statistics)"), Color.Gray);
SetTrayConnectionState(TrayConnectionState.Paused, true);
PersistSessionState();
}
else
{
paused = false;
DateTime now = DateTime.Now;
pauses.Add(new TimePeriod { Start = pauseStart, End = now });
WriteMarker("RESUMED", L.T("繼續監控;暫停 ", "Monitoring resumed; paused for ") + FormatDuration(now - pauseStart));
AddRecent(now, L.T("繼續", "Resumed"), "—", L.T("恢復監控", "Monitoring resumed"), Color.RoyalBlue);
pauseButton.Text = L.T("暫停", "Pause");
UpdateState(L.T("準備檢查…", "Preparing check…"), Color.DarkOrange);
SetTrayConnectionState(TrayConnectionState.Checking, true);
PersistSessionState();
if (timer != null) timer.Change(0, Timeout.Infinite);
RefreshSpeedSchedule();
}
}
private void PerformCheck()
{
if (!running || paused || Interlocked.Exchange(ref checking, 1) == 1) return;
DateTime at = DateTime.Now;
bool online = false;
long latency = 0;
string target = "";
string detail = "";
int nextDelay = checkIntervalSeconds * 1000;
CheckRecord record = null;
bool dismissedSuspected = false;
NetworkSnapshot network = NetworkStatusReader.Capture();
bool networkChanged = currentNetwork == null || currentNetwork.Signature != network.Signature;
try
{
try
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
detail = L.T("Windows 未偵測到可用的網路介面", "Windows detected no available network interface");
}
else
{
var errors = new List<string>();
foreach (string url in activeTestUrls)
{
var sw = Stopwatch.StartNew();
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.UserAgent = "NetCheckMonitor/0.9.15";
request.AllowAutoRedirect = true;
using (var response = (HttpWebResponse)request.GetResponse())
{
sw.Stop();
int code = (int)response.StatusCode;
if (code >= 200 && code < 400)
{
online = true;
latency = sw.ElapsedMilliseconds;
target = new Uri(url).Host;
detail = "HTTP " + code;
break;
}
errors.Add(new Uri(url).Host + ": HTTP " + code);
}
}
catch (Exception ex)
{
sw.Stop();
errors.Add(new Uri(url).Host + ": " + ShortError(ex));
}
}
if (!online) detail = string.Join(L.T(";", "; "), errors.ToArray());
}
}
catch (Exception ex) { detail = ShortError(ex); }
if (online)
{
int retries = consecutiveFailures;
bool recovered = outageConfirmed;
dismissedSuspected = retries > 0 && !outageConfirmed;
DateTime recoveredOutageStart = suspectedStart;
record = new CheckRecord { Time = at, Online = true, LatencyMs = latency, Target = target, Detail = detail, Status = "ONLINE", JustRecovered = recovered, RetryNumber = retries, OutageStart = recoveredOutageStart, Network = network };
ResetOutageTracking();
}
else
{
AdvancedDiagnosticResult diagnostic = null;
if (monitorSettings != null && monitorSettings.AdvancedDiagnosticsEnabled)
{
if (lastAdvancedDiagnostic == null || (at - lastAdvancedDiagnosticAt).TotalSeconds >= 30)
{
lastAdvancedDiagnostic = AdvancedNetworkDiagnostics.Run(network, activeTestUrls);
lastAdvancedDiagnosticAt = at;
}
diagnostic = lastAdvancedDiagnostic;
detail += " || " + diagnostic.ToLogString();
}
consecutiveFailures++;
if (consecutiveFailures == 1) suspectedStart = at;
bool justConfirmed = consecutiveFailures >= 2 && !outageConfirmed;
if (justConfirmed) outageConfirmed = true;
string status = outageConfirmed ? "OFFLINE" : "SUSPECTED";
record = new CheckRecord { Time = at, Online = false, LatencyMs = 0, Target = target, Detail = detail, Status = status, JustConfirmed = justConfirmed, RetryNumber = consecutiveFailures, OutageStart = suspectedStart, Network = network, Diagnostic = diagnostic };
nextDelay = consecutiveFailures <= FastRetryLimit
? FastRetrySeconds * 1000
: Math.Min(checkIntervalSeconds, OutageBackoffSeconds) * 1000;
}
if (!running) return;
if (networkChanged) WriteMarker("NETWORK", network.ToMarker());
currentNetwork = network;
lock (records) records.Add(record);
WriteCheck(record);
if (record.Status == "SUSPECTED") WriteMarker("OUTAGE_SUSPECTED", L.T("首次失敗,5 秒後快速複查", "First failure; fast retry in 5 seconds"));
if (record.JustConfirmed) WriteMarker("OUTAGE_CONFIRMED", L.T("連續失敗,確認斷線;疑似開始:", "Consecutive failures confirmed an outage; suspected start: ") + suspectedStart.ToString("o"));
if (record.JustRecovered) WriteMarker("OUTAGE_RECOVERED", L.T("確認網路已恢復;快速追蹤失敗次數:", "Internet recovery confirmed; fast-tracking failures: ") + record.RetryNumber);
if (dismissedSuspected) WriteMarker("OUTAGE_DISMISSED", L.T("快速複查成功,未形成確認斷線", "Fast retry succeeded; suspected outage dismissed"));
PersistSessionState();
if (record.JustRecovered && gmailManager != null) gmailManager.QueueRecoveryNotification(record.OutageStart, record.Time, record.RetryNumber);
if (!IsDisposed && IsHandleCreated) BeginInvoke((MethodInvoker)delegate { RenderCheck(record); });
}
finally
{
Interlocked.Exchange(ref checking, 0);
ScheduleNextCheck(nextDelay);
}
}
private void ScheduleNextCheck(int delayMilliseconds)
{
if (!running || paused || timer == null) return;
try { timer.Change(Math.Max(1000, delayMilliseconds), Timeout.Infinite); }
catch (ObjectDisposedException) { }
}
private void ResetOutageTracking()
{
consecutiveFailures = 0;
outageConfirmed = false;
suspectedStart = DateTime.MinValue;
lastAdvancedDiagnostic = null;
lastAdvancedDiagnosticAt = DateTime.MinValue;
}
private void PersistSessionState()
{
if (!running || String.IsNullOrEmpty(csvPath)) return;
try
{
lastStateHeartbeat = DateTime.Now;
SessionStateStore.Save(new ActiveSessionState
{
Active = true,
MachineId = machineId,
CsvPath = csvPath,
BackupCsvPath = backupCsvPath,
SessionFileStem = sessionFileStem,
SessionStart = sessionStart,
LastHeartbeat = lastStateHeartbeat,
IntervalSeconds = checkIntervalSeconds,
Paused = paused,
PauseStart = pauseStart,
Targets = new List<string>(activeTestUrls),
UseCustomTargets = monitorSettings != null && monitorSettings.UseCustomTargets,
ConsecutiveFailures = consecutiveFailures,
OutageConfirmed = outageConfirmed,
SuspectedStart = suspectedStart,
ProcessId = Process.GetCurrentProcess().Id,
ProcessStartedUtc = processStartedUtc
});
}
catch (Exception ex) { logWarning = L.T("接續狀態儲存失敗(", "Resume state save failed (") + ex.Message + L.T(")", ")"); }
}
private void HandleStartupMonitoring()
{
try
{
if (UpdateStartup.ResumeAfterUpdate && TryResumeAfterUpdate()) return;
monitorSettings = MonitorSettingsStore.Load();
bool resumeWithoutPrompt = ApplicationStartup.ShouldResumeWithoutPrompt(monitorSettings);
if (TryOfferSessionResume(resumeWithoutPrompt) || running) return;
if (monitorSettings == null || !monitorSettings.AutoStartMonitoring) return;
try { StartMonitoring(); }
catch (Exception ex)
{
MessageBox.Show(L.T("無法自動開始監控:", "Could not start monitoring automatically: ") + ex.Message, "NetCheckMonitor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally { UpdateStartup.SignalHealthy(); }
}
private bool TryResumeAfterUpdate()
{
ActiveSessionState state = SessionStateStore.Load();
if (state == null) return false;
EnsureMachineIdentity();
if (!String.Equals(state.MachineId, machineId, StringComparison.OrdinalIgnoreCase) || !File.Exists(state.CsvPath) || SessionStateStore.IsOriginalProcessAlive(state)) return false;
try
{
ResumeMonitoring(state);
WriteMarker("UPDATE_RESUMED", L.T("程式更新完成並自動接續監控", "Application update completed and monitoring resumed automatically"));
PersistSessionState();
UpdateService.Record("RELAUNCH", "SUCCESS", "Version=" + AboutForm.AppVersion + ";MonitoringResumed=1");
return true;
}
catch (Exception ex)
{
UpdateService.Record("RELAUNCH", "FAILED", ex.Message);
MessageBox.Show(L.T("更新完成,但無法自動接續原本的監控:", "The update completed, but the previous monitoring session could not be resumed automatically: ") + ex.Message, "NetCheckMonitor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return true;
}
}
private bool TryOfferSessionResume(bool resumeWithoutPrompt)
{
if (running) return true;
ActiveSessionState state = SessionStateStore.Load();
if (state == null) return false;
EnsureMachineIdentity();
if (!String.Equals(state.MachineId, machineId, StringComparison.OrdinalIgnoreCase) || !File.Exists(state.CsvPath))
{
SessionStateStore.Delete();
return false;
}
if (SessionStateStore.IsOriginalProcessAlive(state)) return true;
if (resumeWithoutPrompt)
{
try { ResumeMonitoring(state); return true; }
catch (Exception ex)
{
logWarning = L.T("無法自動接續上次監控,已改為建立新的監控工作(", "Could not automatically resume the previous session; a new monitoring session will be started (") + ex.Message + L.T(")", ")");
SessionStateStore.Delete();
return false;
}
}
string message = L.T("發現上次未正常結束的監控工作。\n\n開始時間:", "An unfinished monitoring session was found.\n\nStarted: ")
+ state.SessionStart.ToString("yyyy/MM/dd HH:mm:ss")
+ L.T("\n最後保存:", "\nLast saved: ") + state.LastHeartbeat.ToString("yyyy/MM/dd HH:mm:ss")
+ L.T("\n\n是否接續原本的 CSV 與監控統計?程式未執行的空白時段會標示並排除統計。", "\n\nResume the original CSV and monitoring statistics? Time when the app was not running will be marked and excluded.");
if (MessageBox.Show(message, L.T("接續未完成監控", "Resume Unfinished Monitoring"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try { ResumeMonitoring(state); return true; }
catch (Exception ex)
{
MessageBox.Show(L.T("無法接續監控:", "Could not resume monitoring: ") + ex.Message, "NetCheckMonitor", MessageBoxButtons.OK, MessageBoxIcon.Error);
return true;
}
}
SessionStateStore.Delete();
return false;
}
private void ResumeMonitoring(ActiveSessionState state)
{
records.Clear();
pauses.Clear();
eventNotes.Clear();
recentList.Items.Clear();
LoadSessionHistory(state.CsvPath);
csvPath = state.CsvPath;
backupCsvPath = state.BackupCsvPath;
sessionFileStem = String.IsNullOrWhiteSpace(state.SessionFileStem) ? Path.GetFileNameWithoutExtension(csvPath) : state.SessionFileStem;
sessionStart = state.SessionStart;
intervalBox.Value = Math.Max(intervalBox.Minimum, Math.Min(intervalBox.Maximum, state.IntervalSeconds));
checkIntervalSeconds = (int)intervalBox.Value;
activeTestUrls = state.Targets != null && state.Targets.Count > 0 ? state.Targets.ToArray() : MonitorSettingsStore.GetEffectiveTargets(monitorSettings, TestUrls);
currentNetwork = NetworkStatusReader.Capture();
consecutiveFailures = Math.Max(0, state.ConsecutiveFailures);
outageConfirmed = state.OutageConfirmed;
suspectedStart = state.SuspectedStart;
writer = CreateDurableWriter(csvPath, true);
if (!String.IsNullOrWhiteSpace(backupCsvPath) && !String.Equals(Path.GetFullPath(backupCsvPath), Path.GetFullPath(csvPath), StringComparison.OrdinalIgnoreCase))
{
Directory.CreateDirectory(Path.GetDirectoryName(backupCsvPath));
backupWriter = CreateDurableWriter(backupCsvPath, true);
}
DateTime now = DateTime.Now;
paused = state.Paused;
if (paused)
{
pauseStart = state.PauseStart == DateTime.MinValue ? state.LastHeartbeat : state.PauseStart;
WriteMarker("PROCESS_RESTARTED", L.T("程式重新啟動;原監控維持暫停", "Application restarted; monitoring remains paused"));
}
else
{
DateTime interruption = state.LastHeartbeat > sessionStart && state.LastHeartbeat < now ? state.LastHeartbeat : now;
pauses.Add(new TimePeriod { Start = interruption, End = now });
WriteMarkerAt(interruption, "INTERRUPTED", L.T("程式中斷或電腦關機;此區間不列入統計", "Application interruption or computer shutdown; interval excluded"));
WriteMarkerAt(now, "SESSION_RESUMED", L.T("接續未完成的監控工作", "Unfinished monitoring session resumed"));
}
WriteMarker("NETWORK", currentNetwork.ToMarker());
WriteMarker("POWER_PROTECTION", PowerProtectionMarker(monitorSettings));
running = true;
reportPath = null;
reportButton.Text = L.T("查看報表", "View Report");
reportButton.Enabled = true;
intervalBox.Enabled = false;
UpdateStartButton(true);
settingsButton.Enabled = true;
pauseButton.Enabled = true;
eventNoteButton.Enabled = true;
pauseButton.Text = paused ? L.T("繼續", "Resume") : L.T("暫停", "Pause");
UpdatePowerProtection();
AddRecent(now, L.T("已接續", "Resumed"), "—", L.T("原監控資料已載入;中斷時段不列入統計", "Previous data loaded; interruption excluded from statistics"), Color.RoyalBlue);
UpdateState(paused ? L.T("已接續,維持暫停", "Resumed and still paused") : L.T("已接續,準備檢查…", "Resumed; preparing check…"), paused ? Color.Gray : Color.DarkOrange);
RenderNetworkInfo(currentNetwork);
SetTrayConnectionState(paused ? TrayConnectionState.Paused : TrayConnectionState.Checking, true);
PersistSessionState();
timer = new System.Threading.Timer(delegate { PerformCheck(); }, null, paused ? Timeout.Infinite : 0, Timeout.Infinite);
}
private static string ShortError(Exception ex)
{
if (ex is WebException)
{
var web = (WebException)ex;
if (web.Status == WebExceptionStatus.Timeout) return L.T("逾時", "Timed out");
if (web.Status == WebExceptionStatus.NameResolutionFailure) return L.T("DNS 解析失敗", "DNS resolution failed");
if (web.Status == WebExceptionStatus.ConnectFailure) return L.T("無法連線", "Connection failed");
return web.Status.ToString();
}
return ex.Message.Replace("\r", " ").Replace("\n", " ");
}
private void RenderCheck(CheckRecord record)
{
RenderNetworkInfo(record.Network);
if (record.Status == "SUSPECTED")
{
UpdateState(L.T("疑似斷線,5 秒後快速複查", "Possible outage; fast retry in 5 seconds"), Color.DarkOrange);
SetTrayConnectionState(TrayConnectionState.Checking, true);
AddRecent(record.Time, L.T("疑似斷線", "Suspected"), "—", DisplayCheckDetail(record), Color.DarkOrange);
}
else if (record.Online)
{
string status = record.JustRecovered ? L.T("網路已恢復", "Internet recovered") : L.T("網路正常", "Online");
UpdateState(status, Color.SeaGreen);
SetTrayConnectionState(TrayConnectionState.Online, true);
string rowStatus = record.JustRecovered ? L.T("已恢復", "Recovered") : (record.RetryNumber > 0 ? L.T("複查正常", "Retry online") : L.T("正常", "Online"));
AddRecent(record.Time, rowStatus, record.LatencyMs + " ms", record.Target + L.T("(", " (") + record.Detail + L.T(")", ")"), Color.SeaGreen);
if (record.JustRecovered)
{
trayIcon.Visible = true;
trayIcon.ShowBalloonTip(5000, L.T("NetCheck 網路已恢復", "NetCheck Internet Recovered"), record.Time.ToString("yyyy/MM/dd HH:mm:ss") + L.T(" 已重新連上外部網路", " Internet connectivity has returned"), ToolTipIcon.Info);
}
}
else
{
UpdateState(L.T("已確認斷線,持續追蹤", "Outage confirmed; tracking continues"), Color.Firebrick);
SetTrayConnectionState(TrayConnectionState.Offline, true);
AddRecent(record.Time, record.JustConfirmed ? L.T("確認斷線", "Confirmed outage") : L.T("斷線追蹤", "Outage tracking"), "—", DisplayCheckDetail(record), Color.Firebrick);
if (record.JustConfirmed)
{
trayIcon.Visible = true;
trayIcon.ShowBalloonTip(5000, L.T("NetCheck 確認偵測到斷線", "NetCheck Confirmed an Outage"), record.OutageStart.ToString("yyyy/MM/dd HH:mm:ss") + L.T(" 起連續無法連線到外部網路", " consecutive Internet checks failed"), ToolTipIcon.Error);
}
}
lastLabel.Text = L.T("最後檢查:", "Last check: ") + record.Time.ToString("yyyy/MM/dd HH:mm:ss");
int good = 0, bad = 0;
lock (records) foreach (var r in records) { if (r.Status == "SUSPECTED") continue; if (r.Online) good++; else bad++; }
statsLabel.Text = L.T("有效檢查 ", "Checks ") + (good + bad) + L.T(" 次|正常 ", " | Online ") + good + L.T(" 次|確認失敗 ", " | Confirmed failures ") + bad + L.T(" 次|暫停時間不列入統計", " | Paused time excluded");