-
Notifications
You must be signed in to change notification settings - Fork 0
/
TraceWindow.xaml.cs
827 lines (708 loc) · 30.3 KB
/
TraceWindow.xaml.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
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
#nullable enable
namespace PingTestTool
{
// -------------------- Constants --------------------
public static class Constants
{
public const string DefaultUnresolvedValue = "---";
public const string MsUnitSuffix = " ms";
public const string PercentageSuffix = "%";
public const string DefaultFormat = "F0";
public static class Ping
{
public const int BufferSize = 32;
public const int MaxTtl = 12;
public const int Timeout = 5000;
public const int ParallelRequests = 1;
public const int BaseDelay = 1000;
public const int MinDelay = 100;
public const double HighLossThreshold = 50;
public const double LowLossThreshold = 10;
}
}
// -------------------- Interfaces --------------------
public interface IDnsManager
{
Task<string> GetDomainNameAsync(string ipAddress, CancellationToken token);
}
public interface IPingManager
{
Task StartTraceAsync(string host, CancellationToken token, Action<string, int, string, HopData> updateUiCallback);
void ClearHopData();
}
public interface ITraceWindow
{
bool IsLoaded { get; }
bool IsVisible { get; }
Visibility Visibility { get; set; }
void Show();
void Close();
event EventHandler Closed;
}
// -------------------- Models --------------------
public abstract class ObservableBase : INotifyPropertyChanged
{
private readonly ConcurrentDictionary<string, object> _propertyValues = new();
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetProperty<T>(T value, [CallerMemberName] string? propertyName = null)
{
if (propertyName == null) return false;
var oldValue = _propertyValues.GetOrAdd(propertyName, default(T)!);
if (!EqualityComparer<T>.Default.Equals((T)oldValue, value))
{
_propertyValues[propertyName] = value!;
OnPropertyChanged(propertyName);
return true;
}
return false;
}
protected T GetProperty<T>(T defaultValue = default!, [CallerMemberName] string? propertyName = null) =>
propertyName == null ? defaultValue :
(T)_propertyValues.GetOrAdd(propertyName, defaultValue!);
}
public abstract class ValidationBase
{
protected static void ValidateNotNull<T>(T value, string paramName, ILoggingService logger) where T : class
{
if (value == null)
{
logger.Error($"[{typeof(T).Name}] {paramName} не может быть null.");
throw new ArgumentNullException(paramName);
}
}
protected static void ValidateNotNullOrEmpty(string value, string paramName, ILoggingService logger)
{
if (string.IsNullOrWhiteSpace(value))
{
logger.Error($"[{typeof(ValidationBase).Name}] {paramName} не может быть пустым.");
throw new ArgumentException($"{paramName} не может быть пустым.", paramName);
}
}
}
public class TraceResult : ObservableBase
{
private readonly ILoggingService _logger;
public int Nr
{
get => GetProperty(0);
set => SetProperty(value);
}
public string IPAddress
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string DomainName
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Loss
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Sent
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Received
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Best
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Avrg
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Wrst
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public string Last
{
get => GetProperty(string.Empty);
set => SetProperty(value ?? string.Empty);
}
public TraceResult(ILoggingService logger, int ttl, string ipAddress, string domainName, HopData hop)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
if (hop == null)
{
_logger.Error("[TraceResult] HopData не может быть null.");
throw new ArgumentNullException(nameof(hop));
}
Nr = ttl;
IPAddress = ipAddress;
DomainName = domainName;
UpdateStatistics(hop);
_logger.Information($"[TraceResult] Обновлена статистика для IP: {ipAddress}");
}
public void UpdateStatistics(HopData hop)
{
if (hop == null)
{
_logger.Error("[TraceResult] HopData не может быть null.");
throw new ArgumentNullException(nameof(hop));
}
_logger.Information($"[TraceResult] Обновление статистики для {DomainName}.");
var stats = hop.GetStatistics();
UpdateStatisticsValues(
hop.Sent,
hop.Received,
hop.CalculateLossPercentage(),
stats.Min,
stats.Max,
stats.Avg,
stats.Last
);
}
private void UpdateStatisticsValues(
int sent, int received, double lossPercentage,
long bestTime, long worstTime, double averageTime, long lastTime)
{
_logger.Information($"[TraceResult] Обновление значений статистики: Sent={sent}, Received={received}.");
SetProperty(sent.ToString(), nameof(Sent));
SetProperty(received.ToString(), nameof(Received));
SetProperty($"{lossPercentage.ToString(Constants.DefaultFormat)}{Constants.PercentageSuffix}", nameof(Loss));
SetProperty(FormatMilliseconds(bestTime), nameof(Best));
SetProperty(FormatMilliseconds(worstTime), nameof(Wrst));
SetProperty(FormatMilliseconds((long)averageTime), nameof(Avrg));
SetProperty(FormatMilliseconds(lastTime), nameof(Last));
}
private static string FormatMilliseconds(long milliseconds) =>
$"{milliseconds}{Constants.MsUnitSuffix}";
}
public sealed class HopData
{
private readonly ConcurrentQueue<long> _responseTimes = new();
private readonly ILoggingService _logger;
private readonly object _statsLock = new();
private volatile int _sent;
private volatile int _received;
private long _lastResponseTime;
private (long Min, long Max, double Avg, long Last) _cachedStats;
private volatile bool _statsNeedUpdate = true;
public HopData(ILoggingService logger) =>
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
public int Sent
{
get => _sent;
set => Interlocked.Exchange(ref _sent, value);
}
public int Received
{
get => _received;
set => Interlocked.Exchange(ref _received, value);
}
public void AddResponseTime(long time)
{
if (time < 0)
{
_logger.Error("[HopData] Отрицательное время отклика");
throw new ArgumentOutOfRangeException(nameof(time));
}
_responseTimes.Enqueue(time);
Interlocked.Exchange(ref _lastResponseTime, time);
_statsNeedUpdate = true;
}
public double CalculateLossPercentage() =>
Sent == 0 ? 0 : (double)(Sent - Received) / Sent * 100;
public (long Min, long Max, double Avg, long Last) GetStatistics()
{
if (_responseTimes.IsEmpty)
return (0, 0, 0, 0);
if (!_statsNeedUpdate)
return _cachedStats;
lock (_statsLock)
{
if (!_statsNeedUpdate)
return _cachedStats;
var times = _responseTimes.ToArray();
if (times.Length == 0)
return (0, 0, 0, 0);
_cachedStats = (
times.Min(),
times.Max(),
times.Average(),
_lastResponseTime
);
_statsNeedUpdate = false;
return _cachedStats;
}
}
public void Clear()
{
lock (_statsLock)
{
while (_responseTimes.TryDequeue(out _)) { }
_lastResponseTime = 0;
_statsNeedUpdate = true;
_cachedStats = default;
Sent = Received = 0;
}
}
}
// -------------------- Implementations --------------------
public class DnsManager : ValidationBase, IDnsManager
{
private readonly IMemoryCache _dnsCache;
private readonly TimeSpan _dnsTimeout;
private readonly MemoryCacheEntryOptions _cacheOptions;
private readonly ILoggingService _logger;
public DnsManager(IMemoryCache memoryCache, ILoggingService logger, TimeSpan? dnsTimeout = null)
{
ValidateNotNull(memoryCache, nameof(memoryCache), logger);
ValidateNotNull(logger, nameof(logger), logger);
_dnsCache = memoryCache;
_logger = logger;
_dnsTimeout = dnsTimeout ?? TimeSpan.FromSeconds(5);
_cacheOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30))
.SetSlidingExpiration(TimeSpan.FromMinutes(10));
}
public async Task<string> GetDomainNameAsync(string ipAddress, CancellationToken token)
{
ValidateNotNullOrEmpty(ipAddress, nameof(ipAddress), _logger);
if (!IPAddress.TryParse(ipAddress, out var parsedIp))
{
_logger.Error($"[DnsManager] Некорректный IP-адрес: {ipAddress}");
throw new ArgumentException("Некорректный IP-адрес", nameof(ipAddress));
}
// Попробуем найти результат в кэше
if (_dnsCache.TryGetValue(ipAddress, out string? cachedResult))
{
_logger.Information($"[DnsManager] Кэш найден для {ipAddress}: {cachedResult}");
return cachedResult ?? Constants.DefaultUnresolvedValue;
}
// Если не найдено, попытаться разрешить имя
return await ResolveDomainNameAsync(ipAddress, parsedIp, token);
}
private async Task<string> ResolveDomainNameAsync(string ipAddress, IPAddress parsedIp, CancellationToken token)
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
cts.CancelAfter(_dnsTimeout);
var hostEntry = await Dns.GetHostEntryAsync(parsedIp);
string result = hostEntry.HostName;
// Сохранение результата в кэше
_dnsCache.Set(ipAddress, result, _cacheOptions);
_logger.Information($"[DnsManager] DNS-имя для {ipAddress}: {result}");
return result;
}
catch (Exception ex)
{
_logger.Warning($"[DnsManager] Ошибка при разрешении DNS для {ipAddress}: {ex.Message}");
_dnsCache.Set(ipAddress, Constants.DefaultUnresolvedValue, _cacheOptions);
return Constants.DefaultUnresolvedValue;
}
}
}
public class PingManager : ValidationBase, IPingManager
{
private readonly IDnsManager _dnsManager;
private readonly ConcurrentDictionary<string, HopData> _hopData;
private readonly byte[] _buffer;
private readonly ILoggingService _logger;
public PingManager(IDnsManager dnsManager, ILoggingService logger)
{
ValidateNotNull(dnsManager, nameof(dnsManager), logger);
ValidateNotNull(logger, nameof(logger), logger);
_dnsManager = dnsManager;
_logger = logger;
_hopData = new ConcurrentDictionary<string, HopData>();
_buffer = new byte[Constants.Ping.BufferSize];
}
public async Task StartTraceAsync(string host, CancellationToken token, Action<string, int, string, HopData> updateUiCallback)
{
ValidateNotNullOrEmpty(host, nameof(host), _logger);
ValidateNotNull(updateUiCallback, nameof(updateUiCallback), _logger);
try
{
await ExecuteTracingLoopAsync(host, token, updateUiCallback);
}
finally
{
_logger.Information($"[PingManager] Завершение трассировки для хоста: {host}");
}
}
public void ClearHopData()
{
_hopData.Clear();
_logger.Information("[PingManager] Очищена статистика по хопам");
}
private async Task ExecuteTracingLoopAsync(string host, CancellationToken token, Action<string, int, string, HopData> updateUiCallback)
{
while (!token.IsCancellationRequested)
{
var (maxTtl, delay) = GetTraceParameters();
await ExecuteTraceRoundAsync(host, maxTtl, updateUiCallback, token);
await Task.Delay(delay, token);
}
}
private (int MaxTtl, int Delay) GetTraceParameters()
{
var stats = CalculateLossStatistics();
return (Constants.Ping.MaxTtl, CalculateAdaptiveDelay(stats));
}
private (int TotalSent, int TotalReceived, double LossPercentage) CalculateLossStatistics()
{
int totalSent = _hopData.Values.Sum(h => h.Sent);
int totalReceived = _hopData.Values.Sum(h => h.Received);
double lossPercentage = totalSent > 0 ? (totalSent - totalReceived) / (double)totalSent * 100 : 0;
return (totalSent, totalReceived, lossPercentage);
}
private int CalculateAdaptiveDelay((int TotalSent, int TotalReceived, double LossPercentage) stats)
{
return stats.LossPercentage switch
{
> Constants.Ping.HighLossThreshold => Math.Min(Constants.Ping.Timeout, (int)(Constants.Ping.BaseDelay * 1.5)),
< Constants.Ping.LowLossThreshold => Math.Max(Constants.Ping.MinDelay, (int)(Constants.Ping.BaseDelay * 0.75)),
_ => Constants.Ping.BaseDelay
};
}
private async Task ExecuteTraceRoundAsync(
string host, int maxTtl,
Action<string, int, string,
HopData> updateUiCallback,
CancellationToken token)
{
var pingTasks = Enumerable.Range(1, maxTtl)
.Select(ttl => ExecutePingForTtlAsync(host, ttl, updateUiCallback, token));
await Task.WhenAll(pingTasks);
}
private async Task ExecutePingForTtlAsync(
string host, int ttl,
Action<string, int, string,
HopData> updateUiCallback,
CancellationToken token)
{
var pingTasks = Enumerable.Range(0, Constants.Ping.ParallelRequests)
.Select(_ => ExecuteSinglePingAsync(host, ttl, updateUiCallback, token));
await Task.WhenAll(pingTasks);
}
private async Task ExecuteSinglePingAsync(
string host, int ttl,
Action<string, int, string,
HopData> updateUiCallback,
CancellationToken token)
{
using var pingSender = new Ping();
try
{
var (reply, responseTime) = await SendPingAsync(pingSender, host, ttl, token);
if (reply != null)
{
await ProcessPingReplyAsync(reply, ttl, responseTime, updateUiCallback, token);
}
}
catch (PingException ex)
{
_logger.Warning($"[PingManager] Ошибка пинга {host} с TTL {ttl}: {ex.Message}");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.Error(ex, $"[PingManager] Непредвиденная ошибка: {ex.Message}");
}
}
private async Task<(PingReply? Reply, long ResponseTime)> SendPingAsync(Ping pingSender, string host, int ttl, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var stopwatch = Stopwatch.StartNew();
var reply = await pingSender.SendPingAsync(host, Constants.Ping.Timeout, _buffer, new PingOptions { Ttl = ttl });
stopwatch.Stop();
return (reply, stopwatch.ElapsedMilliseconds);
}
private async Task ProcessPingReplyAsync(
PingReply reply,
int ttl, long responseTime,
Action<string, int, string,
HopData> updateUiCallback,
CancellationToken token)
{
var ipAddress = reply.Address?.ToString() ?? "Неизвестный адрес";
if (!IsValidIpAddress(ipAddress)) return;
var hop = _hopData.GetOrAdd(ipAddress, key => new HopData(_logger));
UpdateHopStatistics(hop, reply, responseTime);
try
{
var domainName = await _dnsManager.GetDomainNameAsync(ipAddress, token);
updateUiCallback(ipAddress, ttl, domainName, hop);
}
catch (OperationCanceledException)
{
_logger.Warning($"[PingManager] Запрос доменного имени для {ipAddress} отменен.");
updateUiCallback(ipAddress, ttl, ipAddress, hop);
}
catch (Exception ex)
{
_logger.Warning($"[PingManager] Не удалось получить доменное имя для {ipAddress}; используется IP. {ex.Message}");
updateUiCallback(ipAddress, ttl, ipAddress, hop);
}
}
private static bool IsValidIpAddress(string ipAddress)
=> !string.IsNullOrEmpty(ipAddress) && ipAddress.Trim() != "0.0.0.0";
private static void UpdateHopStatistics(HopData hop, PingReply reply, long responseTime)
{
lock (hop) // минимизация гонок
{
hop.Sent++;
if (reply.Status is IPStatus.Success or IPStatus.TtlExpired or IPStatus.TimeExceeded)
{
hop.Received++;
hop.AddResponseTime(responseTime);
}
}
}
}
public class TraceManager : ValidationBase, IDisposable
{
private CancellationTokenSource? _cts;
private bool _disposed;
private readonly IPingManager _pingManager;
private readonly IDnsManager _dnsManager;
private readonly ILoggingService _logger;
private readonly ObservableCollection<TraceResult> _traceResults;
private readonly IMemoryCache _memoryCache;
private bool _isTracing;
public ObservableCollection<TraceResult> TraceResults => _traceResults;
public string TraceUrl { get; }
public bool IsTracing
{
get => _isTracing;
private set => _isTracing = value;
}
public TraceManager(string url, ILoggingService logger)
{
ValidateNotNullOrEmpty(url, nameof(url), logger);
ValidateNotNull(logger, nameof(logger), logger);
TraceUrl = url;
_logger = logger;
_traceResults = new ObservableCollection<TraceResult>();
_memoryCache = new MemoryCache(new MemoryCacheOptions());
_dnsManager = new DnsManager(_memoryCache, logger);
_pingManager = new PingManager(_dnsManager, logger);
_logger.Information($"[TraceManager] Инициализирован с URL: {url}");
}
public async Task StartTraceAsync(Action<string, Color> updateStatus, Action<string, string, MessageBoxButton, MessageBoxImage> showMessage)
{
if (!ValidateTraceStart(showMessage)) return;
IsTracing = true;
updateStatus("Трассировка запущена...", Colors.Green);
_logger.Information($"[TraceManager] Запуск трассировки для URL: {TraceUrl}");
_cts?.Dispose();
_cts = new CancellationTokenSource();
try
{
await _pingManager.StartTraceAsync(TraceUrl, _cts.Token, UpdateHopStatistics);
}
catch (OperationCanceledException)
{
_logger.Warning("[TraceManager] Трассировка отменена");
}
catch (Exception ex)
{
HandleTraceError(ex, showMessage);
}
finally
{
ResetTraceStatus(updateStatus);
}
}
private bool ValidateTraceStart(Action<string, string, MessageBoxButton, MessageBoxImage> showMessage)
{
if (IsTracing)
{
showMessage("Трассировка уже запущена.", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
_logger.Warning("[TraceManager] Попытка запустить уже запущенную трассировку");
return false;
}
return true;
}
private void HandleTraceError(Exception ex, Action<string, string, MessageBoxButton, MessageBoxImage> showMessage)
{
_logger.Error(ex, $"[TraceManager] Ошибка: {ex.Message}");
showMessage($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
public void StopTrace()
{
try
{
_cts?.Cancel();
_logger.Information("[TraceManager] Трассировка остановлена");
}
catch (Exception ex)
{
_logger.Error(ex, "[TraceManager] Ошибка при остановке трассировки");
}
}
public void ClearResults()
{
_traceResults.Clear();
_pingManager.ClearHopData();
_logger.Information("[TraceManager] Результаты очищены");
}
private void UpdateHopStatistics(string ipAddress, int ttl, string domainName, HopData hop)
{
if (string.IsNullOrEmpty(ipAddress))
{
_logger.Warning("[TraceManager] Получен пустой IP-адрес");
return;
}
try
{
Application.Current.Dispatcher.Invoke(() =>
{
var existingResult = _traceResults.FirstOrDefault(tr => tr.IPAddress == ipAddress);
if (existingResult is null)
{
_traceResults.Add(new TraceResult(_logger, ttl, ipAddress, domainName, hop));
_logger.Information($"[TraceManager] Добавлен новый результат для IP: {ipAddress}");
}
else
{
existingResult.UpdateStatistics(hop);
_logger.Information($"[TraceManager] Обновлена статистика для IP: {ipAddress}");
}
});
}
catch (Exception ex)
{
_logger.Error(ex, "[TraceManager] Ошибка при обновлении статистики хопа");
}
}
private void ResetTraceStatus(Action<string, Color> updateStatus)
{
IsTracing = false;
updateStatus("Трассировка остановлена.", Colors.Red);
_logger.Information("[TraceManager] Статус трассировки сброшен");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_cts?.Dispose();
_memoryCache?.Dispose();
}
_disposed = true;
}
~TraceManager()
{
Dispose(false);
}
}
public partial class TraceWindow : Window, ITraceWindow
{
private readonly TraceManager _traceManager;
private readonly ILoggingService _logger;
public ICollectionView TraceResults { get; }
public TraceWindow(string url, ILoggingService logger)
{
InitializeComponent();
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_traceManager = new TraceManager(url, _logger);
TraceResults = ConfigureTraceResults();
_logger.Information($"[TraceWindow] Инициализирован с URL: {url}");
}
private ICollectionView ConfigureTraceResults()
{
var view = CollectionViewSource.GetDefaultView(_traceManager.TraceResults);
ResultsList.ItemsSource = view;
((CollectionView)view).SortDescriptions.Add(new SortDescription("Nr", ListSortDirection.Ascending));
return view;
}
private async void BtnStartTrace_Click(object sender, RoutedEventArgs e)
{
await HandleTraceStartAsync();
}
private async Task HandleTraceStartAsync()
{
if (!ValidateTraceStart()) return;
SetTraceControlsState(isStarting: true);
await _traceManager.StartTraceAsync(UpdateStatus, ShowMessage);
}
private bool ValidateTraceStart()
{
if (_traceManager.IsTracing)
{
ShowMessage("Трассировка уже запущена.", "Предупреждение");
_logger.Warning("[TraceWindow] Попытка запустить уже запущенную трассировку");
return false;
}
if (string.IsNullOrWhiteSpace(_traceManager.TraceUrl))
{
ShowMessage("Пожалуйста, укажите URL для трассировки.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
_logger.Error("[TraceWindow] URL для трассировки не указан");
return false;
}
return true;
}
private void SaveResults(string fileName)
{
try
{
File.WriteAllLines(fileName, _traceManager.TraceResults.Select(result => result?.ToString() ?? "Пустой результат"));
ShowMessage("Результаты успешно сохранены.", "Успех");
_logger.Information($"[TraceWindow] Результаты сохранены в файл: {fileName}");
}
catch (Exception ex)
{
ShowMessage($"Ошибка при сохранении результатов: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
_logger.Error(ex, $"[TraceWindow] Ошибка при сохранении результатов: {ex.Message}");
}
}
private void ShowMessage(string message, string title, MessageBoxButton button = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.Information)
=> MessageBox.Show(message, title, button, icon);
private void UpdateStatus(string message, Color color)
=> StatusTextBlock.Dispatcher.Invoke(() =>
{
StatusTextBlock.Text = message;
StatusTextBlock.Foreground = new SolidColorBrush(color);
});
private void BtnClearResults_Click(object sender, RoutedEventArgs e)
{
_traceManager.ClearResults();
_logger.Information("[TraceWindow] Результаты очищены");
}
private void BtnStopTrace_Click(object sender, RoutedEventArgs e)
{
_traceManager.StopTrace();
UpdateStatus("Остановка трассировки...", Colors.Orange);
_logger.Information("[TraceWindow] Трассировка остановлена");
SetTraceControlsState(isStarting: false);
}
private void SetTraceControlsState(bool isStarting)
{
btnStartTrace.IsEnabled = !isStarting;
btnStopTrace.IsEnabled = isStarting;
}
private void BtnSaveResults_Click(object sender, RoutedEventArgs e)
{
var saveFileDialog = new SaveFileDialog
{
Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
};
if (saveFileDialog.ShowDialog() == true)
{
SaveResults(saveFileDialog.FileName);
}
}
}
}