Repository navigation
Expand file tree
/
Copy pathTracerouteViewModel.cs
More file actions
521 lines (422 loc) · 14.5 KB
/
Copy pathTracerouteViewModel.cs
File metadata and controls
521 lines (422 loc) · 14.5 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
using log4net;
using MahApps.Metro.Controls;
using MahApps.Metro.SimpleChildWindow;
using NETworkManager.Controls;
using NETworkManager.Localization.Resources;
using NETworkManager.Models;
using NETworkManager.Models.EventSystem;
using NETworkManager.Models.Export;
using NETworkManager.Models.Network;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using NETworkManager.Views;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
namespace NETworkManager.ViewModels;
/// <summary>
/// ViewModel for the Traceroute feature.
/// </summary>
public class TracerouteViewModel : ViewModelBase
{
#region Variables
private static readonly ILog Log = LogManager.GetLogger(typeof(TracerouteViewModel));
private CancellationTokenSource _cancellationTokenSource;
private readonly Guid _tabId;
private bool _firstLoad = true;
private bool _closed;
/// <summary>
/// Gets or sets the host address or hostname to trace.
/// </summary>
public string Host
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the collection view for the host history.
/// </summary>
public ICollectionView HostHistoryView { get; }
/// <summary>
/// Gets or sets a value indicating whether a traceroute is currently running.
/// </summary>
public bool IsRunning
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the trace should be cancelled.
/// </summary>
public bool CancelTrace
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets the collection of traceroute hop results.
/// </summary>
public ObservableCollection<TracerouteHopInfo> Results
{
get;
set
{
if (Equals(value, field))
return;
field = value;
}
} = new();
/// <summary>
/// Gets the collection view for the traceroute results.
/// </summary>
public ICollectionView ResultsView { get; }
/// <summary>
/// Gets or sets the currently selected traceroute result hop.
/// </summary>
public TracerouteHopInfo SelectedResult
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets the list of currently selected traceroute result hops (for multi-selection).
/// </summary>
public IList SelectedResults
{
get;
set
{
if (Equals(value, field))
return;
field = value;
OnPropertyChanged();
}
} = new ArrayList();
private bool _ipGeolocationRateLimitIsReached;
/// <summary>
/// Gets or sets a value indicating whether the status message is displayed.
/// </summary>
public bool IsStatusMessageDisplayed
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the status message to display.
/// </summary>
public string StatusMessage
{
get;
private set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
#endregion
#region Constructor, load settings
/// <summary>
/// Initializes a new instance of the <see cref="TracerouteViewModel"/> class.
/// </summary>
/// <param name="tabId">The unique identifier for the tab.</param>
/// <param name="host">The initial host to trace.</param>
public TracerouteViewModel(Guid tabId, string host)
{
ConfigurationManager.Current.TracerouteTabCount++;
_tabId = tabId;
Host = host;
// Set collection view
HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Traceroute_HostHistory);
// Result view
ResultsView = CollectionViewSource.GetDefaultView(Results);
ResultsView.SortDescriptions.Add(new SortDescription(nameof(TracerouteHopInfo.Hop),
ListSortDirection.Ascending));
LoadSettings();
}
/// <summary>
/// Called when the view is loaded. Starts the trace if it's the first load and a host is specified.
/// </summary>
public void OnLoaded()
{
if (!_firstLoad)
return;
if (!string.IsNullOrEmpty(Host))
_ = StartTrace();
_firstLoad = false;
}
private void LoadSettings()
{
}
#endregion
#region ICommands & Actions
/// <summary>
/// Gets the command to start or stop the traceroute.
/// </summary>
public ICommand TraceCommand => new RelayCommand(_ => TraceAction(), Trace_CanExecute);
private bool Trace_CanExecute(object parameter)
{
return Application.Current.MainWindow != null &&
!((MetroWindow)Application.Current.MainWindow)!.IsAnyDialogOpen &&
!ConfigurationManager.Current.IsChildWindowOpen;
}
private void TraceAction()
{
if (IsRunning)
StopTrace();
else
_ = StartTrace();
}
/// <summary>
/// Gets the command to redirect the selected result's data to another application.
/// </summary>
public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction);
private void RedirectDataToApplicationAction(object name)
{
if (name is not ApplicationName applicationName)
return;
var host = !string.IsNullOrEmpty(SelectedResult.Hostname)
? SelectedResult.Hostname
: SelectedResult.IPAddress.ToString();
EventSystem.RedirectToApplication(applicationName, host);
}
/// <summary>
/// Gets the command to perform a DNS lookup for the selected hop.
/// </summary>
public ICommand PerformDNSLookupCommand => new RelayCommand(PerformDNSLookupAction);
private void PerformDNSLookupAction(object data)
{
EventSystem.RedirectToApplication(ApplicationName.DNSLookup, data.ToString());
}
/// <summary>
/// Gets the command to copy the round-trip time to the clipboard.
/// </summary>
public ICommand CopyTimeToClipboardCommand => new RelayCommand(CopyTimeToClipboardAction);
private void CopyTimeToClipboardAction(object timeIdentifier)
{
var time = timeIdentifier switch
{
"1" => Ping.TimeToString(SelectedResult.Status1, SelectedResult.Time1),
"2" => Ping.TimeToString(SelectedResult.Status2, SelectedResult.Time2),
"3" => Ping.TimeToString(SelectedResult.Status3, SelectedResult.Time3),
_ => "-/-"
};
ClipboardHelper.SetClipboard(time);
}
/// <summary>
/// Gets the command to export the traceroute results.
/// </summary>
public ICommand ExportCommand => new RelayCommand(_ => ExportAction());
private void ExportAction()
{
_ = Export();
}
#endregion
#region Methods
private void StopTrace()
{
CancelTrace = true;
_cancellationTokenSource.Cancel();
}
private async Task StartTrace()
{
_ipGeolocationRateLimitIsReached = false;
StatusMessage = string.Empty;
IsStatusMessageDisplayed = false;
IsRunning = true;
Results.Clear();
DragablzTabItem.SetTabHeader(_tabId, Host);
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = new CancellationTokenSource();
// Try to parse the string into an IP-Address
if (!IPAddress.TryParse(Host, out var ipAddress))
{
var dnsResult =
await DNSClientHelper.ResolveAorAaaaAsync(Host,
SettingsManager.Current.Network_ResolveHostnamePreferIPv4);
if (dnsResult.HasError)
{
DisplayStatusMessage(DNSClientHelper.FormatDNSClientResultError(Host, dnsResult));
IsRunning = false;
return;
}
ipAddress = dnsResult.Value;
}
try
{
var traceroute = new Traceroute(new TracerouteOptions(
SettingsManager.Current.Traceroute_Timeout,
new byte[SettingsManager.Current.Traceroute_Buffer],
SettingsManager.Current.Traceroute_MaximumHops,
true,
SettingsManager.Current.Traceroute_ResolveHostname,
SettingsManager.Current.Traceroute_CheckIPApiIPGeolocation
));
traceroute.HopReceived += Traceroute_HopReceived;
traceroute.TraceComplete += Traceroute_TraceComplete;
traceroute.MaximumHopsReached += Traceroute_MaximumHopsReached;
traceroute.TraceError += Traceroute_TraceError;
traceroute.UserHasCanceled += Traceroute_UserHasCanceled;
traceroute.TraceAsync(ipAddress, _cancellationTokenSource.Token);
// Add the host to history
AddHostToHistory(Host);
}
catch (Exception ex) // This will catch any exception
{
IsRunning = false;
DisplayStatusMessage(ex.Message);
}
}
private Task Export()
{
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
var childWindow = new ExportChildWindow();
var childWindowViewModel = new ExportViewModel(async instance =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
try
{
ExportManager.Export(instance.FilePath, instance.FileType,
instance.ExportAll
? Results
: SelectedResults.Cast<TracerouteHopInfo>().ToArray());
}
catch (Exception ex)
{
Log.Error("Error while exporting data as " + instance.FileType, ex);
await DialogHelper.ShowMessageAsync(window, Strings.Error,
Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine +
Environment.NewLine + ex.Message, ChildWindowIcon.Error);
}
SettingsManager.Current.Traceroute_ExportFileType = instance.FileType;
SettingsManager.Current.Traceroute_ExportFilePath = instance.FilePath;
}, _ =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
}, [
ExportFileType.Csv, ExportFileType.Xml, ExportFileType.Json
], true, SettingsManager.Current.Traceroute_ExportFileType,
SettingsManager.Current.Traceroute_ExportFilePath);
childWindow.Title = Strings.Export;
childWindow.DataContext = childWindowViewModel;
ConfigurationManager.Current.IsChildWindowOpen = true;
return window.ShowChildWindowAsync(childWindow);
}
private void AddHostToHistory(string host)
{
// Create the new list
var list = ListHelper.Modify(SettingsManager.Current.Traceroute_HostHistory.ToList(), host,
SettingsManager.Current.General_HistoryListEntries);
// Clear the old items
SettingsManager.Current.Traceroute_HostHistory.Clear();
OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared
// Fill with the new items
list.ForEach(x => SettingsManager.Current.Traceroute_HostHistory.Add(x));
}
public void OnClose()
{
// Prevent multiple calls
if (_closed)
return;
_closed = true;
// Stop trace
if (IsRunning)
StopTrace();
ConfigurationManager.Current.TracerouteTabCount--;
}
#endregion
#region Events
private void Traceroute_HopReceived(object sender, TracerouteHopReceivedArgs e)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate
{
// Check error
if (e.Args.IPGeolocationResult.HasError)
{
Log.Error(
$"ip-api.com error: {e.Args.IPGeolocationResult.ErrorMessage}, error code: {e.Args.IPGeolocationResult.ErrorCode}");
DisplayStatusMessage($"ip-api.com: {e.Args.IPGeolocationResult.ErrorMessage}");
}
// Check rate limit
if (!_ipGeolocationRateLimitIsReached && e.Args.IPGeolocationResult.RateLimitIsReached)
{
_ipGeolocationRateLimitIsReached = true;
Log.Warn(
$"ip-api.com rate limit reached. Try again in {e.Args.IPGeolocationResult.RateLimitRemainingTime} seconds.");
DisplayStatusMessage(
$"ip-api.com {string.Format(Strings.RateLimitReachedTryAgainInXSeconds, e.Args.IPGeolocationResult.RateLimitRemainingTime)}");
}
Results.Add(e.Args);
}));
}
private void Traceroute_MaximumHopsReached(object sender, MaximumHopsReachedArgs e)
{
DisplayStatusMessage(string.Format(Strings.MaximumNumberOfHopsReached, e.Hops));
IsRunning = false;
}
private void Traceroute_UserHasCanceled(object sender, EventArgs e)
{
DisplayStatusMessage(Strings.CanceledByUserMessage);
CancelTrace = false;
IsRunning = false;
}
private void Traceroute_TraceError(object sender, TracerouteErrorArgs e)
{
DisplayStatusMessage(e.ErrorMessage);
IsRunning = false;
}
private void Traceroute_TraceComplete(object sender, EventArgs e)
{
IsRunning = false;
}
private void DisplayStatusMessage(string message)
{
if (!string.IsNullOrEmpty(StatusMessage))
StatusMessage += Environment.NewLine;
StatusMessage += message;
IsStatusMessageDisplayed = true;
}
#endregion
}