forked from BornToBeRoot/NETworkManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSNMPViewModel.cs
More file actions
792 lines (620 loc) · 20.4 KB
/
Copy pathSNMPViewModel.cs
File metadata and controls
792 lines (620 loc) · 20.4 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using Dragablz;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using NETworkManager.Controls;
using NETworkManager.Localization;
using NETworkManager.Localization.Resources;
using NETworkManager.Models.Export;
using NETworkManager.Models.Network;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using NETworkManager.Views;
namespace NETworkManager.ViewModels;
public class SNMPViewModel : ViewModelBase
{
#region Contructor, load settings
public SNMPViewModel(IDialogCoordinator instance, Guid tabId, SNMPSessionInfo sessionInfo)
{
_isLoading = true;
_dialogCoordinator = instance;
ConfigurationManager.Current.SNMPTabCount++;
_tabId = tabId;
Host = sessionInfo?.Host;
// Set collection view
HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_HostHistory);
OidHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_OidHistory);
// Result view
ResultsView = CollectionViewSource.GetDefaultView(QueryResults);
// Custom comparer to sort by OID
((ListCollectionView)ResultsView).CustomSort = Comparer<SNMPInfo>.Create((x, y) =>
SNMPOIDHelper.CompareOIDs(x.OID, y.OID));
// OID
Oid = sessionInfo?.OID;
// Modes
Modes = new List<SNMPMode> { SNMPMode.Get, SNMPMode.Walk, SNMPMode.Set };
Mode = Modes.FirstOrDefault(x => x == sessionInfo?.Mode);
// Versions (v1, v2c, v3)
Versions = Enum.GetValues(typeof(SNMPVersion)).Cast<SNMPVersion>().ToList();
Version = Versions.FirstOrDefault(x => x == sessionInfo?.Version);
// Community
if (Version != SNMPVersion.V3)
Community = sessionInfo?.Community;
// Security
Securities = new List<SNMPV3Security>
{ SNMPV3Security.NoAuthNoPriv, SNMPV3Security.AuthNoPriv, SNMPV3Security.AuthPriv };
Security = Securities.FirstOrDefault(x => x == sessionInfo?.Security);
// Username
if (Version == SNMPVersion.V3)
Username = sessionInfo?.Username;
// Auth
AuthenticationProviders = Enum.GetValues(typeof(SNMPV3AuthenticationProvider))
.Cast<SNMPV3AuthenticationProvider>().ToList();
AuthenticationProvider = AuthenticationProviders.FirstOrDefault(x => x == sessionInfo?.AuthenticationProvider);
if (Version == SNMPVersion.V3 && Security != SNMPV3Security.NoAuthNoPriv)
Auth = sessionInfo?.Auth;
// Priv
PrivacyProviders = Enum.GetValues(typeof(SNMPV3PrivacyProvider)).Cast<SNMPV3PrivacyProvider>().ToList();
PrivacyProvider = PrivacyProviders.FirstOrDefault(x => x == sessionInfo?.PrivacyProvider);
if (Version == SNMPVersion.V3 && Security == SNMPV3Security.AuthPriv)
Priv = sessionInfo?.Priv;
_isLoading = false;
}
#endregion
#region Variables
private readonly IDialogCoordinator _dialogCoordinator;
private CancellationTokenSource _cancellationTokenSource;
private readonly Guid _tabId;
private readonly bool _isLoading;
private bool _closed;
private string _host;
public string Host
{
get => _host;
set
{
if (value == _host)
return;
_host = value;
OnPropertyChanged();
}
}
public ICollectionView HostHistoryView { get; }
public IEnumerable<SNMPMode> Modes { get; set; }
private SNMPMode _mode;
public SNMPMode Mode
{
get => _mode;
set
{
if (value == _mode)
return;
if (!_isLoading)
SettingsManager.Current.SNMP_Mode = value;
_mode = value;
OnPropertyChanged();
// Re-validate OID if mode changed
OnPropertyChanged(nameof(Oid));
}
}
public IEnumerable<SNMPVersion> Versions { get; }
private SNMPVersion _version;
public SNMPVersion Version
{
get => _version;
set
{
if (value == _version)
return;
if (!_isLoading)
SettingsManager.Current.SNMP_Version = value;
_version = value;
OnPropertyChanged();
}
}
private string _oid;
public string Oid
{
get => _oid;
set
{
if (value == _oid)
return;
_oid = value;
OnPropertyChanged();
}
}
public ICollectionView OidHistoryView { get; }
public IEnumerable<SNMPV3Security> Securities { get; }
private SNMPV3Security _security;
public SNMPV3Security Security
{
get => _security;
set
{
if (value == _security)
return;
if (!_isLoading)
SettingsManager.Current.SNMP_Security = value;
_security = value;
OnPropertyChanged();
}
}
private bool _isCommunityEmpty = true; // Initial it's empty
public bool IsCommunityEmpty
{
get => _isCommunityEmpty;
set
{
if (value == _isCommunityEmpty)
return;
_isCommunityEmpty = value;
OnPropertyChanged();
}
}
private SecureString _community;
public SecureString Community
{
get => _community;
set
{
if (value == _community)
return;
// Validate the community string
IsCommunityEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value));
_community = value;
OnPropertyChanged();
}
}
private string _username;
public string Username
{
get => _username;
set
{
if (value == _username)
return;
_username = value;
OnPropertyChanged();
}
}
public IEnumerable<SNMPV3AuthenticationProvider> AuthenticationProviders { get; }
private SNMPV3AuthenticationProvider _authenticationProvider;
public SNMPV3AuthenticationProvider AuthenticationProvider
{
get => _authenticationProvider;
set
{
if (value == _authenticationProvider)
return;
if (!_isLoading)
SettingsManager.Current.SNMP_AuthenticationProvider = value;
_authenticationProvider = value;
OnPropertyChanged();
}
}
private bool _isAuthEmpty = true; // Initial it's empty
public bool IsAuthEmpty
{
get => _isAuthEmpty;
set
{
if (value == _isAuthEmpty)
return;
_isAuthEmpty = value;
OnPropertyChanged();
}
}
private SecureString _auth;
public SecureString Auth
{
get => _auth;
set
{
if (value == _auth)
return;
// Validate the auth string
IsAuthEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value));
_auth = value;
OnPropertyChanged();
}
}
public IEnumerable<SNMPV3PrivacyProvider> PrivacyProviders { get; }
private SNMPV3PrivacyProvider _privacyProvider;
public SNMPV3PrivacyProvider PrivacyProvider
{
get => _privacyProvider;
set
{
if (value == _privacyProvider)
return;
if (!_isLoading)
SettingsManager.Current.SNMP_PrivacyProvider = value;
_privacyProvider = value;
OnPropertyChanged();
}
}
private bool _isPrivEmpty = true; // Initial it's empty
public bool IsPrivEmpty
{
get => _isPrivEmpty;
set
{
if (value == _isPrivEmpty)
return;
_isPrivEmpty = value;
OnPropertyChanged();
}
}
private SecureString _priv;
public SecureString Priv
{
get => _priv;
set
{
if (value == _priv)
return;
// Validate the auth string
IsPrivEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value));
_priv = value;
OnPropertyChanged();
}
}
private string _data = string.Empty;
public string Data
{
get => _data;
set
{
if (value == _data)
return;
_data = value;
OnPropertyChanged();
}
}
private bool _isRunning;
public bool IsRunning
{
get => _isRunning;
set
{
if (value == _isRunning)
return;
_isRunning = value;
OnPropertyChanged();
}
}
private bool _cancelScan;
public bool CancelScan
{
get => _cancelScan;
set
{
if (value == _cancelScan)
return;
_cancelScan = value;
OnPropertyChanged();
}
}
private ObservableCollection<SNMPInfo> _queryResults = [];
public ObservableCollection<SNMPInfo> QueryResults
{
get => _queryResults;
set
{
if (Equals(value, _queryResults))
return;
_queryResults = value;
}
}
public ICollectionView ResultsView { get; }
private SNMPInfo _selectedResult;
public SNMPInfo SelectedResult
{
get => _selectedResult;
set
{
if (value == _selectedResult)
return;
_selectedResult = value;
OnPropertyChanged();
}
}
private IList _selectedResults = new ArrayList();
public IList SelectedResults
{
get => _selectedResults;
set
{
if (Equals(value, _selectedResults))
return;
_selectedResults = value;
OnPropertyChanged();
}
}
private bool _isStatusMessageDisplayed;
public bool IsStatusMessageDisplayed
{
get => _isStatusMessageDisplayed;
set
{
if (value == _isStatusMessageDisplayed)
return;
_isStatusMessageDisplayed = value;
OnPropertyChanged();
}
}
private string _statusMessage;
public string StatusMessage
{
get => _statusMessage;
private set
{
if (value == _statusMessage)
return;
_statusMessage = value;
OnPropertyChanged();
}
}
#endregion
#region ICommands & Actions
public ICommand WorkCommand => new RelayCommand(_ => WorkAction(), Work_CanExecute);
private bool Work_CanExecute(object parameter)
{
return Application.Current.MainWindow != null &&
!((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen;
}
private void WorkAction()
{
Work();
}
public ICommand OpenOIDProfilesCommand => new RelayCommand(_ => OpenOIDProfilesAction());
private void OpenOIDProfilesAction()
{
OpenOIDProfileSelection().ConfigureAwait(false);
}
public ICommand ExportCommand => new RelayCommand(_ => ExportAction());
private void ExportAction()
{
Export().ConfigureAwait(false);
}
#endregion
#region Methods
private void Work()
{
if (IsRunning)
StopWork();
else
StartWork();
}
private async void StartWork()
{
IsStatusMessageDisplayed = false;
IsRunning = true;
QueryResults.Clear();
DragablzTabItem.SetTabHeader(_tabId, Host);
// 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)
{
StatusMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult);
IsStatusMessageDisplayed = true;
IsRunning = false;
return;
}
ipAddress = dnsResult.Value;
}
_cancellationTokenSource = new CancellationTokenSource();
// SNMP...
SNMPClient snmpClient = new();
snmpClient.Received += SNMPClient_Received;
snmpClient.DataUpdated += SNMPClient_DataUpdated;
snmpClient.Error += SNMPClient_Error;
snmpClient.Canceled += SNMPClient_Canceled;
snmpClient.Complete += SNMPClient_Complete;
var oidValue = Oid.Replace(" ", "");
// Check if we have multiple OIDs for a Get request
List<string> oids = new();
if (Mode == SNMPMode.Get && oidValue.Contains(';'))
oids.AddRange(oidValue.Split(';'));
else
oids.Add(oidValue);
// SNMPv1 or v2c
if (Version != SNMPVersion.V3)
{
var snmpOptions = new SNMPOptions(
Community,
Version,
SettingsManager.Current.SNMP_Port,
SettingsManager.Current.SNMP_WalkMode,
_cancellationTokenSource.Token
);
switch (Mode)
{
case SNMPMode.Get:
snmpClient.GetAsync(ipAddress, oids, snmpOptions);
break;
case SNMPMode.Walk:
snmpClient.WalkAsync(ipAddress, oids[0], snmpOptions);
break;
case SNMPMode.Set:
snmpClient.SetAsync(ipAddress, oids[0], Data, snmpOptions);
break;
}
}
// SNMPv3
else
{
var snmpOptionsV3 = new SNMPOptionsV3(
Security,
Username,
AuthenticationProvider,
Auth,
PrivacyProvider,
Priv,
SettingsManager.Current.SNMP_Port,
SettingsManager.Current.SNMP_WalkMode,
_cancellationTokenSource.Token
);
switch (Mode)
{
case SNMPMode.Get:
snmpClient.GetAsyncV3(ipAddress, oids, snmpOptionsV3);
break;
case SNMPMode.Walk:
snmpClient.WalkAsyncV3(ipAddress, oids[0], snmpOptionsV3);
break;
case SNMPMode.Set:
snmpClient.SetAsyncV3(ipAddress, oids[0], Data, snmpOptionsV3);
break;
}
}
// Set timeout
_cancellationTokenSource.CancelAfter(SettingsManager.Current.SNMP_Timeout);
// Add to history...
AddHostToHistory(Host);
AddOidToHistory(Oid);
}
private void StopWork()
{
CancelScan = true;
_cancellationTokenSource.Cancel();
}
public void OnClose()
{
// Prevent multiple calls
if (_closed)
return;
_closed = true;
ConfigurationManager.Current.SNMPTabCount--;
}
private async Task OpenOIDProfileSelection()
{
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
var customDialog = new CustomDialog
{
Title = Strings.SelectOIDProfile
};
var viewModel = new SNMPOIDProfilesViewModel(async instance =>
{
await _dialogCoordinator.HideMetroDialogAsync(window, customDialog);
Mode = instance.SelectedOIDProfile.Mode;
Oid = instance.SelectedOIDProfile.OID;
}, async _ => { await _dialogCoordinator.HideMetroDialogAsync(window, customDialog); });
customDialog.Content = new SNMPOIDProfilesDialog
{
DataContext = viewModel
};
await _dialogCoordinator.ShowMetroDialogAsync(window, customDialog);
}
private void AddHostToHistory(string host)
{
// Create the new list
var list = ListHelper.Modify(SettingsManager.Current.SNMP_HostHistory.ToList(), host,
SettingsManager.Current.General_HistoryListEntries);
// Clear the old items
SettingsManager.Current.SNMP_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.SNMP_HostHistory.Add(x));
}
private void AddOidToHistory(string oid)
{
// Create the new list
var list = ListHelper.Modify(SettingsManager.Current.SNMP_OidHistory.ToList(), oid,
SettingsManager.Current.General_HistoryListEntries);
// Clear the old items
SettingsManager.Current.SNMP_OidHistory.Clear();
OnPropertyChanged(nameof(Oid)); // Raise property changed again, after the collection has been cleared
// Fill with the new items
list.ForEach(x => SettingsManager.Current.SNMP_OidHistory.Add(x));
}
private async Task Export()
{
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
var customDialog = new CustomDialog
{
Title = Strings.Export
};
var exportViewModel = new ExportViewModel(async instance =>
{
await _dialogCoordinator.HideMetroDialogAsync(window, customDialog);
try
{
ExportManager.Export(instance.FilePath, instance.FileType,
instance.ExportAll
? QueryResults
: new ObservableCollection<SNMPInfo>(SelectedResults.Cast<SNMPInfo>().ToArray()));
}
catch (Exception ex)
{
var settings = AppearanceManager.MetroDialog;
settings.AffirmativeButtonText = Strings.OK;
await _dialogCoordinator.ShowMessageAsync(window, Strings.Error,
Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine +
Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings);
}
SettingsManager.Current.SNMP_ExportFileType = instance.FileType;
SettingsManager.Current.SNMP_ExportFilePath = instance.FilePath;
}, _ => { _dialogCoordinator.HideMetroDialogAsync(window, customDialog); }, [
ExportFileType.Csv, ExportFileType.Xml, ExportFileType.Json
], true, SettingsManager.Current.SNMP_ExportFileType, SettingsManager.Current.SNMP_ExportFilePath);
customDialog.Content = new ExportDialog
{
DataContext = exportViewModel
};
await _dialogCoordinator.ShowMetroDialogAsync(window, customDialog);
}
#endregion
#region Events
private void SNMPClient_Received(object sender, SNMPReceivedArgs e)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate { QueryResults.Add(e.Args); }));
}
private void SNMPClient_DataUpdated(object sender, EventArgs e)
{
StatusMessage = Strings.DataHasBeenUpdated;
IsStatusMessageDisplayed = true;
}
private void SNMPClient_Error(object sender, SNMPErrorArgs e)
{
if (e.IsErrorCode)
StatusMessage = ResourceTranslator.Translate(ResourceIdentifier.SNMPErrorCode, e.ErrorCode);
else if (e.IsErrorCodeV3)
StatusMessage = ResourceTranslator.Translate(ResourceIdentifier.SNMPV3ErrorCode, e.ErrorCodeV3);
else
StatusMessage = e.ErrorMessage;
IsStatusMessageDisplayed = true;
}
private void SNMPClient_Canceled(object sender, EventArgs e)
{
StatusMessage = CancelScan
? Strings.CanceledByUserMessage
: Strings.TimeoutOnSNMPQuery;
IsStatusMessageDisplayed = true;
}
private void SNMPClient_Complete(object sender, EventArgs e)
{
CancelScan = false;
IsRunning = false;
}
#endregion
}